leetcode每日一题(2020.09.30) 701. 二叉搜索树中的插入操作

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

leetcode每日一题(2020.09.30) 701. 二叉搜索树中的插入操作_第1张图片
leetcode每日一题(2020.09.30) 701. 二叉搜索树中的插入操作_第2张图片
leetcode每日一题(2020.09.30) 701. 二叉搜索树中的插入操作_第3张图片

1.迭代(anan)(和官解很像)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {        
        if(root == null){
            //return null;
            /* 该错误对应案例
            []
            5       
            */
            TreeNode s = new TreeNode(val, null, null);
            return s;
        }
        TreeNode node = root;
        while(node != null){
            if(val > node.val){
                //if(node.left == null && node.right == null){  //叶子节点
                if(node.right == null){ 
                    TreeNode s = new TreeNode(val, null, null);
                    node.right = s;
                    break;
                }else{
                    node = node.right;
                }               
            }else if(val < node.val){
                //if(node.left == null && node.right == null){  //叶子节点
                /* 该错误对应案例           
                [5,null,14,10,77,null,null,null,95,null,null]
                4
                */
                if(node.left == null){ 
                    TreeNode s = new TreeNode(val, null, null);
                    node.left = s;
                    break;
                }else{
                    node = node.left;
                } 
            }
        }

        return root;
    }
}

2.递归(别人家的)(漂亮)

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {        
        if(root == null){
            return new TreeNode(val);
        }

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

你可能感兴趣的:(LeetCode,java)