[LintCode]Insert Node in a Binary Search Tree
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
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) {
// 2015-3-30
if (node == null) {
return root;
}
if (root == null) {
return node;
}
TreeNode temp = root;
TreeNode last = null;
boolean left = true;
while (temp != null) {
if (temp.val < node.val) {
last = temp;
temp = temp.right;
left = false;
} else if (temp.val > node.val) {
last = temp;
temp = temp.left;
left = true;
} else {
return root;
}
}
if (left == true) {
last.left = node;
} else {
last.right = node;
}
return root;
}
}