Problem

Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

Example

Given binary search tree as follow, after Insert node 6, the tree should be:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6

Challenge

Can you do it without recursion?

Note

建立两个树结点,先用cur找到node在BST的位置,让pre作为cur的根节点;找到node的位置后,cur指向null。此时,用node代替cur与pre连接就可以了。返回root。

Solution

public class Solution {
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null) return node;
        TreeNode cur = root, pre = null;
        while (cur != null) {
            pre = cur;
            if (cur.val > node.val) cur = cur.left;
            else cur = cur.right;
        }
        if (pre != null) {
            if (pre.val > node.val) pre.left = node;
            else pre.right = node;
        }
        return root;
    }
}

linspiration
161 声望53 粉丝