235.二叉搜索树的最近公共祖先
题目链接/文章讲解: 代码随想录
代码随想录
二叉树的最近公共结点核心思路是自下向上回溯检验两侧是否包含p或q,二叉搜索树有序,公共结点一定在[p,q]区间内,这里一定是左闭右闭
所以当我们从上向下去递归遍历,第一次遇到 cur节点是数值在[q, p]区间中,那么cur就是 q和p的最近公共祖先。
代码
class Solution {
TreeNode ancestor = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int pInt = p.val;
int qInt = q.val;
if(pInt>qInt){
int temp =pInt;
pInt = qInt;
qInt = temp;
}
getCommonNFather(root,pInt,qInt);
return ancestor;
}
public void getCommonNFather(TreeNode root,int low,int high) {
if(root==null)return;
if(root.val>=low&&root.val<=high){
ancestor = root;
return;
}
getCommonNFather(root.left,low,high);
getCommonNFather(root.right, low, high);
}
}
701.二叉搜索树中的插入操作
代码随想录
插入任何值都是按照BST规则在空结点处做延申,并不需要改变指针。
这道题特别的是用返回值完成新加入的节点与其父节点的赋值操作。
终止条件:
//终止条件,只要找到空指针插入就行
if(root==null){
TreeNode treeNode = new TreeNode(val);
return treeNode;
}
将新加入的结点返回给上一层
单层递归逻辑:
if(root.val<val)root.right = insertIntoBST(root.right,val);
if(root.val>val)root.left = insertIntoBST(root.left,val);
下层将新加入结点返回,父节点用root.left 和 root.right接住
代码
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
//终止条件,只要找到空指针插入就行
if(root==null){
TreeNode treeNode = new TreeNode(val);
return treeNode;
}
if(root.val<val)root.right = insertIntoBST(root.right,val);
if(root.val>val)root.left = insertIntoBST(root.left,val);
return root;
}
}
450.删除BST的节点
题目链接/文章讲解: 代码随想录
代码随想录
五种情况 :
- 没找到
- 叶子节点,左右都空 ,返回null
- 左为空,右不为空,右结点直接指向父节点,返回 root.right
- 左不空,右为空,左节点直接指向父节点 , 返回 root.left
- 左右都不为空,右节点继承,左子树的新父节点为原右子树的最小值 ,返回root.right
本题不遍历整颗二叉树,找到要删除的结点并且删除也就结束了,这就是终止条件。
父节点用root.left 和 root.right接住删除结点后新的根节点,返回的都是新要接上去的结点。
class Solution {
TreeNode pre = null;
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null)return null;
if(root.val==key){
if(root.left==null&&root.right==null)return null;
else if(root.left!=null&&root.right==null)return root.left;
else if(root.left==null&&root.right!=null)return root.right;
else{
TreeNode cur = root.right;
while (cur.left!=null&&cur.right!=null){
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
}
if(root.val>key) root.left = deleteNode(root.left,key);
if(root.val<key)root.right = deleteNode(root.right,key);
return root;
}
}