LCA 类问题
-
LCA 类问题是二叉树的高频问题之一;
-
有只给 root 的;
-
还有不给 root 给 parent pointer 的。
-
想面 FB,最好把各种二叉树问题的 recursion / iteration 还有 root / parent pointer 的写法都练熟才行,只 AC 是不够的。
下面这种向哪里走的问题,直接用尾递归解决。不要想遍历。
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Got to check if p and q is null as well;
if(root == null) return root;
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;
}
}
因为是尾递归,显而易见的改法是用 while循环省去递归占用的系统栈空间;
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Got to check if p and q is null as well;
while(root != null){
if(root.val > p.val && root.val > q.val) root = root.left;
else if(root.val < p.val && root.val < q.val) root = root.right;
else return root;
}
return root;
}
}
Lowest Common Ancestor of a Binary Tree
时间复杂度 O(n),相对于每个 node 来讲,只会被函数调用和计算一次。
另一种时间复杂度的分析方式是,这题的递归结构是个 post-order traversal,遍历的复杂度当然是 O(n).
拿到树的题目,先想递归结构是什么,再想end condition.
想到这,迭代的写法也比较明显了,写个 post-order traversal 就行。
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == q || root == p) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) return root;
else return (left == null) ? right : left;
}
}