1.二叉搜索树的最近公共祖先
思路:这道题与二叉树的最近公共祖先不同的点在于:二叉搜索树自带分叉属性,当root.val处于pq(假设p<q)之间时,p必然在root.left,q必然在root.right,
重点:在递归语句前加个判断,就可以实现单边递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//注意题目没讲p>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;
}
}
2..二叉搜索树中的插入操作
.二叉搜索树就是好用,还是单边递归查询就行
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null)
return new TreeNode(val);
if(val < root.val)
root.left = insertIntoBST(root.left,val);
if(val > root.val)
root.right = insertIntoBST(root.right,val);
return root;
}
}
3.删除二叉搜索树中的节点
删除节点挺难的,主要是判断5中情况,有点递归结合迭代那意思了
1.如果没有key,没什么好说的,直接返回null,就像普通的二叉搜索树递归一样
2.找到了key,root。val==key
2.1root的子节点左空右不空,那就返回roo.right,root的父节点的右来接住他(递归的体现)
2.2root的子节点左不空右空,那就返回roo.left,root的父节点的左来接住他(递归的体现)
2.3左右都不空,那就把root.left连接到root.right.left上,如果这个位置已经有人了,那就往左下角层层找到空的,(二叉搜索树的特性:一个节点的左节点一定会比他的所有右节点小)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
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{
//创建这个cur就是为了好遍历的,因为我们要先把roo.left安顿好,他是要比root.right的所有左子树都要小的,所以找到root.right的最小left就行
TreeNode cur = root.right;
while(cur.left != null)
cur = cur.left;
//安顿root.left;
cur.left = root.left;
//直接返回root.right,有点像链表中的删除节点
return root.right;
}
}
if(key < root.val)
root.left = deleteNode(root.left,key);
if(key > root.val)
root.right = deleteNode(root.right,key);
return root;
}
}