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

深度优先搜索

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        /**
         * 如果找到了p或者q,就返回
         */
        if (root == null || root == p || root == q){
            return root;
        }

        /**
         * 分别在左右子树进行递归查找,如果返回值为空,说明q和p都不在这棵树上,那肯定在另一颗树上
         * 如果两棵树返回值都不为空,说明q和p分别在左右两边,那root就是唯一的公共祖先
         */
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right= lowestCommonAncestor(root.right, p, q);

        if (left == null){
            return right;
        }
        else if (right == null){
            return left;
        }
        else {
            return root;
        }
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

posted @ 2021-12-27 10:26  振袖秋枫问红叶  阅读(33)  评论(0)    收藏  举报