235. 二叉搜索树的最近公共祖先
本题无关前中后序:对于BST,如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的
- 普通二叉树的最近公共祖先:回溯,需要后序遍历
- BST的递增数组:中序遍历
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) return root;
lower = p.val>q.val? q : p;
bigger = p.val>q.val? p : q;
return find(root);
}
private TreeNode lower;
private TreeNode bigger;
private TreeNode find(TreeNode node){ // 判断获取到:非null
if(node==null) return null;
if(node.val>=lower.val && node.val<=bigger.val){ // 一个在左,一个在右
return node;
}
TreeNode left = find(node.left);
if(left!=null) return left;
TreeNode right = find(node.right);
if(right!=null) return right;
return null;
}
}
代码随想录解法:
- 不关心p、q谁大谁小,只要不在区间,就递归。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
701.二叉搜索树中的插入操作
遇到空节点,直接插入即可。
虽然题目说可以重构二叉树,但没必要。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode nodeNew = new TreeNode(val);
if(root==null) return nodeNew;
TreeNode cur = root;
while(cur!=null){
if(val < cur.val){
if(cur.left==null){
cur.left = nodeNew;
return root;
}
cur = cur.left;
}else if(val > cur.val){
if(cur.right==null){
cur.right = nodeNew;
return root;
}
cur = cur.right;
}
}
return root;
}
}
代码随想录递归解法:
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) // 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。
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;
}
}
450.删除二叉搜索树中的节点
思路:将return的node作为节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null) return root;
if(key < root.val){
root.left = deleteNode(root.left, key);
}else if(key > root.val){
root.right = deleteNode(root.right, key);
}else{
if(root.left==null && root.right==null) return null;
else if(root.left!=null && root.right!=null){
TreeNode cur = root.right.left;
while(cur!=null){ // 最后指向空节点
if(root.left.val > cur.val) {
if(cur.right==null) {
cur.right = root.left;
break;
}
cur = cur.right;
}else{
if(cur.left==null){
cur.left = root.left;
break;
}
cur = cur.left;
}
}
if(cur==null) root.right.left = root.left;
return root.right;
}else if(root.left!=null && root.right==null){
return root.left;
}else if(root.left==null && root.right!=null){
return root.right;
}
}
return root;
}
}