236. 二叉树的最近公共祖先
由于需要从下向上回溯,选用后序遍历
当找到这两个节点或者空时返回该节点,先进行左右递归,然后处理该节点:都找到时才返回该节点,因为是后序所以肯定返回最下层也就是最近的公共祖先,左右之一找不到时就说明,最近公共祖先是p和q中的一个,就返回另一边。都找不到就返回null。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p,q);
TreeNode right= lowestCommonAncestor(root.right,p,q);
if (left == null && right == null) return null;
if (left == null) return right;
if (right== null) return left;
return root;
}
}
235. 二叉搜索树的最近公共祖先
在上一题的基础上加了二叉搜索树的条件,相当于二叉树变成了有序数组,因为公共祖先节点一定在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) {
if (root == null) return new TreeNode(val);
if (root.val > val) root.left = insertIntoBST(root.left, val);
if (root.val < val) root.right =insertIntoBST(root.right,val);
return root;
}
}
450.删除二叉搜索树中的节点
跟上一题相比复杂一些,将删除节点的左孩子放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (key == root.val) {
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;
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;
}
}