236. 二叉树的最近公共祖先

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先从上向下遍历,找到就返回。以后一层一层的回溯。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// if(root == null) {
// return null;
// }
// TreeNode left = lowestCommonAncestor(root.left,p,q);
// TreeNode right = lowestCommonAncestor(root.right,p,q);
// // 回溯找,找到了;
// if(root == p || root == q) {
// return root;
// } else {
// // 没有找到
// if(left != null && right != null) {
// return root;
// } else if(left != null || right != null) {
// return left == null ? right : left;
// } else {
// return null;
// }
// }
if(root == null) {
return null;
}
// 找到就返回
if(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;
} else if(left != null || right != null) { // 只有一个有,就返回有数据的。
return left != null ? left :right;
} else { // 如果都没有,返回null
return null;
}
}
注释掉的逻辑是从下至上回溯找。
浙公网安备 33010602011771号