美文网首页
701. 二叉搜索树中的插入操作

701. 二叉搜索树中的插入操作

作者: Andysys | 来源:发表于2020-02-02 11:03 被阅读0次
    // 递归
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } else if (val > root.val) {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }

    // 迭代
    public TreeNode insertIntoBST2(TreeNode root, int val) {
        TreeNode p = root;
        while (p != null) {
            if (val > p.val) {
                if (p.right == null) {
                    p.right = new TreeNode(val);
                    return root;
                } else {
                    p = p.right;
                }
            } else if (val < p.val) {
                if (p.left == null) {
                    p.left = new TreeNode(val);
                    return root;
                } else {
                    p = p.left;
                }
            }
        }
        return root;
    }

相关文章

网友评论

      本文标题:701. 二叉搜索树中的插入操作

      本文链接:https://www.haomeiwen.com/subject/ocieoctx.html