讨论/《二叉搜索树》 - 二叉搜索树中的插入操作/
《二叉搜索树》 - 二叉搜索树中的插入操作
共 2 个回复
/**
 * 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) {
        root = insert(root, val);
        return root;
    }

    private TreeNode insert(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        int cmp = val - root.val;
        if (cmp == 0) {

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

}

Java

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