85. Insert Node in a Binary Search Tree【easy】

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.

Notice

You can assume there is no duplicate values in this tree + node.

 
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?

解法一:

 public class Solution {
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
public TreeNode insertNode(TreeNode root, TreeNode node) {
if (root == null) {
return node;
}
if (root.val > node.val) {
root.left = insertNode(root.left, node);
} else {
root.right = insertNode(root.right, node);
}
return root;
}
}

解法二:

 public class Solution {
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
public TreeNode insertNode(TreeNode root, TreeNode node) {
if (root == null) {
root = node;
return root;
}
TreeNode tmp = root;
TreeNode last = null;
while (tmp != null) {
last = tmp;
if (tmp.val > node.val) {
tmp = tmp.left;
} else {
tmp = tmp.right;
}
}
if (last != null) {
if (last.val > node.val) {
last.left = node;
} else {
last.right = node;
}
}
return root;
}
}

解法三:

 class Solution {
public:
/*
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
TreeNode * insertNode(TreeNode * root, TreeNode * node) {
stack<TreeNode * > sta;
sta.push(root);
TreeNode * last = NULL;
while (sta.size() != ) {
TreeNode * now = sta.top();
sta.pop();
if (now == NULL) {
if (last == NULL) {
root = node;
} else if (last->val <= node->val) {
last -> right = node;
} else {
last -> left = node;
}
break;
} else if (now->val <= node->val) {
sta.push(now->right);
} else {
sta.push(now->left);
}
last = now;
}
return root;
}
};

参考@DLNU-linglian 的代码

上一篇:jQuery扩展extend一


下一篇:进程通信---FIFO