每日一道Leetcode——二叉搜索树中的插入操作

题目:
每日一道Leetcode——二叉搜索树中的插入操作_第1张图片
解法一:递归

/**
 * 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 new TreeNode(val);
        }

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

官方题解:

/**
 * 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 new TreeNode(val);
        }

        TreeNode t = root;
        while(t!=null){
            if(t.val<val){
                if(t.right==null){
                    t.right = new TreeNode(val);
                    break;
                }
                t = t.right;
            }else{
                if(t.left==null){
                    t.left = new TreeNode(val);
                    break;
                }
                t = t.left;
            }
        }
        return root;
        
    }
}

你可能感兴趣的:(leetcode,算法,java,二叉树)