二叉搜索树的插入操作

293 阅读1分钟

题目

二叉树的递归

    public TreeNode insertIntoBST(TreeNode root, int val) {
        // 遍历二叉树, 寻找合适的插入位置
        if (root == null) {
            return new TreeNode(val);
        }

        if (root.val < val) {
            root.right = insertIntoBST(root.right, val);
        } else {
            root.left = insertIntoBST(root.left, val);
        }

        return root;
    }

基本思路

  1. 递归遍历二叉树, 如果目标值比当前值大, 就遍历右节点, 否则遍历左节点

  2. 遇见当前节点为null, 就将目标值插入