leetcode:236 二叉树的最近公共祖先 (java代码实现)
解题思路
后序遍历二叉树 假设遍历到的当前结点为cur 先处理左子树和右子树 left和right
如果cur为null 或者为p和q中的任意一个 直接返回cur
如果left和right都不为null 返回cur
如果left不为null 返回left
如果right不为null 返回right
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 root;
}
return left != null ? left : right;
}