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

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

【找到要插入的点的父节点】思路就是二分查找那种的,先查找这个点应该插入的位置,判定条件为null,那么null的父节点就是第一个小于这个插入点的节点,所以直接创建节点作为他的左儿子即可;但是也有例外,就是要查找的点很大很大,这样应该是做右儿子才行。因此需要在最后插入的时候做一次判断。

class Solution {

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) return new TreeNode(val);
        TreeNode pre = new TreeNode(), dummy = root;
        while(true){
            if(root == null) break;
            pre = root;
            if(root.val < val) root = root.right;
            else root = root.left;
        }
        if(pre.val < val) pre.right = new TreeNode(val);
        else pre.left = new TreeNode(val);
        return dummy;
    }
}

【优化】 其实还有更好的方法,就是在查找的过程中直接把这件事情做了,如果:

1.查找节点不为null,就根据大小继续向左向右查找;

2.查找节点为null,创建新节点替换null

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值