这篇page是针对leetcode136.二叉树的最近公共祖先。小尼先简单的说明一下这道题的意思,给定一个二叉树,找到该树中两个指定节点的最近公共祖先。
这里直接运用后序遍历和递归的方法解决就行了,小尼先拉一下代码:
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;
}else if(left == null && right != null) {
return right;
}else if(left != null && right == null) {
return left;
}else {
return root;
}
}
}