【树】701. 二叉搜索树中的插入操作 ( 第一次遇到 超过内存限制)

题目:

给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。

 

解答:

方法一:

这里使用了递归栈,题目出现 超出内存范围 提示

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {

        if(root == null) {
            return new TreeNode(val);
        }

        if(root.left==null&&root.right==null){
            TreeNode node = new TreeNode(val);
            if(root.val>val){
                root.left = node;
            }else{
                root.right = node;
            }
        }

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

        return root;
    }

}

 

 

方法二:不用递归,直接遍历

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {

        if(root == null) {
            return new TreeNode(val);
        }

        TreeNode p = root;
        while(p!=null){
            if(p.val>val){
                if(p.left == null){
                    p.left = new TreeNode(val);
                    break;
                }
                else{
                    p = p.left;
                }
            }
            else{
                if(p.right == null){
                    p.right = new TreeNode(val);
                    break;
                }
                else{
                    p = p.right;
                }
            }
        }

        return root;
    }
    
   
}

 

posted @ 2020-10-23 22:27  3KBLACK  阅读(100)  评论(0)    收藏  举报