题目(难度:中等):
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和 插入的值: 5
你可以返回这个二叉搜索树:
4 / \ 2 7 / \ / 1 3 5
代码思想:
利用递归思想,判断该值如果比当前节点值大,则转移到右子树;如果比当前节点值小,则转移到左子树,直到叶子节点时结束,插入该值。
代码实现:
public TreeNode insertIntoBST(TreeNode root, int val) {
/*根节点为空*/
if (root == null) return new TreeNode(val);
/*根节点不为空,左右子树为空*/
if (root != null && root.left == null && root.right == null) {
if (root.val < val) {
root.right = new TreeNode(val);
return root;
} else {
root.left = new TreeNode(val);
return root;
}
}
if (root.val < val) {
if (root.right == null) {
root.right = new TreeNode(val);
return root;
}
insertIntoBST(root.right, val);
}
if (root.val > val) {
if (root.left == null) {
root.left = new TreeNode(val);
return root;
}
insertIntoBST(root.left, val);
}
return root;
}
测试用例:
算法分析:
遍历整棵树,时间复杂度O(n);额外空间复杂度O(1)