236. 二叉树的最近公共祖先 + 递归方法
236. 二叉树的最近公共祖先
题目描述
相似题目:https://www.cnblogs.com/GarrettWale/p/14406641.html
题解分析
- 此题是利用二叉树的后序遍历来求解最近公共祖先。
- 递归的出口是遍历到叶子结点或者当前结点(root)等于待搜索的结点(p或者q),此时需要返回root。
- 如果左右子树中均没有找到(返回null)说明p或者q都不在左右子树,当前root肯定不是最近公共祖先。
- 如果左右子树均不为空,说明p和q分布在当前结点的左右两侧。
- 如果有一边为空(left或者right),说明p或者q在非空的一侧(此时可能两个都在那颗非空的子树上,也有可能只有一个在)。
代码实现
/**
* 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) {
if(root == null || p == root || q == root)
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;
}
}
Either Excellent or Rusty