Description:
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
For example,
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to insert: 5
You can return this binary search tree:
4
/ \
2 7
/ \ /
1 3 5
This tree is also valid:
5
/ \
2 7
/ \
1 3
\
4
题意:将一个新的节点插入到二叉搜索树中(可能会有多种解法);
解法:我们知道对于二叉搜索树的每个节点来说,都满足以下两个条件
- root.val > root.left.val
- root.val < root.right.val
因此,我们只需要遍历到那些没有左孩子或右孩子的节点,按照值的大小关系插入即可;
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root.left == null && val < root.val) {
root.left = new TreeNode(val);
return root;
}
if (root.right == null && val > root.val) {
root.right = new TreeNode(val);
return root;
}
if (val > root.val) {
insertIntoBST(root.right, val);
}
if (val < root.val) {
insertIntoBST(root.left, val);
}
return root;
}
}