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.
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
思路
- 如果待插入节点A < 根值, 插入到root的左子树,
- 如果A > 根值, 插入到root的右子树
public TreeNode insertNode(TreeNode root, TreeNode node) {
if (root == null) {
return node;
}
if (node.val < root.val) {
root.left = insertNode(root.left, node);
} else {
root.right = insertNode(root.right, node);
}
return root;
}