目录
235 二叉搜索树的最近公共祖先
p与q有如下三种情况:
- 分别位于最近公共祖先节点的左右子树中
- 一同位于最近公共祖先节点的左或右子树中
- 一个位于中间节点,另一个位于其子树中
根据二叉搜索树的有序性,p与q的最近公共祖先一定在[p,q]内,我们最先找到的节点root,能使得 q.val<=root.val<=p.val 或者p.val<=root.val<=q.val,则该节点就是所求的答案。
递归
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val < p.val && root.val < q.val)return lowestCommonAncestor(root.right,p,q);
if(root.val > p.val && root.val > q.val)return lowestCommonAncestor(root.left,p,q);
return root;
}
}
时间复杂度O(n)
空间复杂度O(h)二叉搜索树的深度
迭代
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(true){
if(root.val < p.val && root.val < q.val)root = root.right;
else if(root.val > p.val && root.val > q.val)root = root.left;
else break;
}
return root;
}
}
时间复杂度O(n)
空间复杂度O(1)
701 二叉搜索树中的插入操作
依照二叉搜索树的性质,遍历到空节点后插入相应元素即可。
递归
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null)return new TreeNode(val);//当前节点为空,说明找到了合适的位置,插入即可
if(root.val > val)root.left = insertIntoBST(root.left,val);//说明应该插入位置在左子树
else if(root.val < val)root.right = insertIntoBST(root.right,val);//说明应该插入位置在右子树
return root;
}
}
时间复杂度O(n)
空间复杂度O(h)
迭代
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null)return new TreeNode(val);
TreeNode cur = root;
TreeNode pre = root;
while(cur != null){
pre = cur;
if(val > cur.val){
cur = cur.right;
}else if(val < cur.val){
cur = cur.left;
}
}
if(val > pre.val)pre.right = new TreeNode(val);
else pre.left = new TreeNode(val);
return root;
}
}
时间复杂度O(n)
空间复杂度O(h)
450 删除二叉搜索树中的节点
依照二叉搜索树的性质,有如下五种情况:
- 没找到目标节点且遍历到空节点,返回NULL
- 找到目标节点,该节点的左右节点均为空,删除该节点返回NULL
- 找到目标节点,该节点的左节点为空,右节点不为空,删除该节点后返回右节点
- 找到目标节点,该节点的右节点为空,左节点不为空,删除该节点后返回左节点
- 找到目标节点,该节点的左右节点均不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null)return root;
if(root.val == key){
if(root.left == null)return root.right;
else if(root.right == null)return root.left;
else{
TreeNode cur = root.right;
while (cur.left != null) {
cur = cur.left;
}
cur.left = root.left;
root = root.right;
return root;
}
}
if(key < root.val)root.left = deleteNode(root.left,key);
if(key > root.val)root.right = deleteNode(root.right,key);
return root;
}
}
时间复杂度O(n)
空间复杂度O(n)n为二叉树节点的个数,递归的深度最深为O(n)
文章出处登录后可见!
已经登录?立即刷新