我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/description/
题目描述:
知识点:二分搜索树
由于二分搜索树天然的递归结构,很多和二分搜索树有关的算法都可以用递归实现。
递归的终止条件:
当root为空时,直接返回一个新节点,其值为val。
递归的过程:
(1)当root的值小于val时,将val添加进root的右子树中,并令root的右孩子为添加了val节点的右子树。
(1)当root的值大于val时,将val添加进root的左子树中,并令root的左孩子为添加了val节点的左子树。
时间复杂度是O(h)级别的,h为树的深度。空间复杂度就是递归深度,也是O(h)级别的。
JAVA代码:
public class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) {
return new TreeNode(val);
}
if(root.val < val) {
root.right = insertIntoBST(root.right, val);
}else if(root.val > val) {
root.left = insertIntoBST(root.left, val);
}
return root;
}
}
LeetCode解题报告:
抛开递归,我们完全可以像在链表中寻找插入点的前一个节点一样在二分搜索树中寻找插入点的前一个节点。在二分搜索树中插入点的前一个节点,如果val的值大于这个节点的值,那么val节点一定成为该节点的右孩子。如果val的值小于这个节点的值,那么val节点一定成为该节点的左孩子。
整个插入过程如下:
(1)如果root为空时,直接返回一个新节点,其值为val。
(2)否则令cur指针指向root节点,只要cur指针不为空,就进行以下循环:
a.如果cur节点的值大于val,如果cur的左孩子为空,则新建一个值为val的节点,令其为cur的左孩子。如果cur的左孩子不为空,令cur指向cur的左孩子。
b.如果cur节点的值小于val,如果cur的右孩子为空,则新建一个值为val的节点,令其为cur的右孩子。如果cur的右孩子不为空,令cur指向cur的右孩子。
JAVA代码:
public class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) {
return new TreeNode(val);
}
TreeNode cur = root;
while(cur != null) {
if(cur.val < val) {
if(cur.right == null) {
cur.right = new TreeNode(val);
return root;
}else {
cur = cur.right;
}
}else {
if(cur.left == null) {
cur.left = new TreeNode(val);
return root;
}else {
cur = cur.left;
}
}
}
return root;
}
}
LeetCode解题报告: