leetcode 701. 二叉搜索树中的插入操作【BST】

方法1:

递归实现,当插入值比当前节点值小时,向左子树搜索;当插入值比当前节点值大时,向右子树搜索。当递归到终点(root==null)时,构造我们需要插入的节点,并返回该节点。
注意:递归左、右子树时,需要将新生成的左、右子树的根节点地址赋值给其父节点的左、右引用。

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null){
            TreeNode t = new TreeNode(val);
            return t;
        }else {
            if(val < root.val){
                root.left = insertIntoBST(root.left, val);
            }else if(val>root.val){
                root.right = insertIntoBST(root.right, val);
            }
        }
        return root;
    }
}

方法2:

除了使用递归,还可以使用循环的方式来实现。

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        TreeNode t = root;
        while(root != null){
            if(val < root.val){
                if(root.left == null){
                    root.left = new TreeNode(val);
                    return t;
                }
                root = root.left;
            }else{
                if(root.right == null){
                    root.right = new TreeNode(val);
                    return t;
                }
                root = root.right;
            }
        }
        return t;
    }
}
发布了55 篇原创文章 · 获赞 0 · 访问量 771

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/105080466
今日推荐