85. Insert Node in a Binary Search Tree
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
Example 1:
Input: tree = {}, node = 1
Output: 1
Explanation:
Insert node 1 into the empty tree, so there is only one node on the tree.
Example 2:
Input: tree = {2,1,4,3}, node = 6
Output: {2,1,4,3,6}
Explanation:
Like this:
2 2
/ /
1 4 --> 1 4
/ /
3 3 6
Challenge
Can you do it without recursion?
思路:
在树上定位要插入节点的位置。
- 如果它大于当前根节点,则应该在右子树中,如果没有右子树则将该点作为右儿子插入;若存在右子树则在右子树中继续定位。
- 如果它小于当前根节点,则应该在左子树中,处理同上。
(二叉查找树中保证不插入已经存在的值)
二分法代码:
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; }