Leetcode 236 Lowest Common Ancestor of a Binary Tree 笔记

164 阅读1分钟

Medium

思路

  • DFS,个人认为原因如下,因为是寻找最小的祖先,所以与BFS的初衷恰好相反(BFS常用于寻找离根结点最近的解)。另外当遇到Example2 的情况时,DFS的back tracking意义重大,刚好可以满足要求。
  • 做了好多DFS的题才理解: DFS中的base case不是返回给主函数!是自己的次级返回给自己的上一级!!! 好菜啊!
  • 两种情况
    1. 左右都返回来值了,说明两个点在这个点的左右两边,向上返回这个点
    1. 左右只有一个返回值,另一个是null,说明还是在一侧,那么不能确定在哪里交汇,所以一直返回那个得到的值
  • base case: 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;
        if(left == null && right != null) return right;
        else
            return left;
    }
}