Insert Node in BST

题目:
在BST中插入节点。

解题思路:
这道题可以用iterative和recursive两种方法来解。

代码:

public class InsertNodeinBST {

    public TreeNode insertNodeInterative(TreeNode root, TreeNode node) {
        // write your code here        if(root == null){
            return node;
        }
        TreeNode curt = root;
        while(curt != node){
            if(node.val < curt.val){
                if(curt.left == null){
                    curt.left = node;
                }
                curt = curt.left;
            }else{
                if(curt.right == null){
                    curt.right = node;
                }
                curt = curt.right;
            }
        }
        return root;
    }

    public TreeNode insertNodeRecursice(TreeNode root, TreeNode node) {
        if (root == null) {
            return node;
        }
        if (root.val > node.val) {
            root.left = insertNodeRecursice(root.left, node);
        } else {
            root.right = insertNodeRecursice(root.right, node);
        }
        return root;
    }

}

Comments

Popular Posts