leetcode236_二叉树的最近公共祖先
拿到这个题目首先想到的就是希望能够自底向上,
应该使用回溯,回溯是天然的自底向上。
后序遍历就是天然的回溯,最先处理的一定是叶子节点。
那么要走递归三部曲:
-
确定返回值和参数
-
确定终止条件
-
循环体
-
确定返回值和参数
其实这道题最基本的想法应该是用boolean来表示root中能否找到p和q,不过可以用TreeNode是否为null来表示能找到与否。所以这里使用题目中给出的函数签名即可。 -
终止条件
其实终止条件可以不止一个,如果为空说明找不到,如果为p或者q他们自身就能找到自己也可以直接返回root。 -
单层逻辑体
我们需要对整个棵树进行遍历,需要用两个状态变量来接受对左右子树的遍历结果。
如果只在一个,说明LCA由它返回的,直接返回不为空的。
如果两个都有,那就说明是根节点。
否则为null。
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 root;
else if(left == null && right != null) return right;
else if(left != null && right == null) return left;
else return null;
}
}