【DFS】LeetCode 236. 二叉树的最近公共祖先

题目链接

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

思路

image

代码

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);

        // p and q are not in left subtree
        if(left == null){
            return right;
        }
        // p and q are not in right subtree
        if(right == null){
            return left;
        }

        // p and q are in the left subtree and right subtree respectively
        return root;
    }
}
posted @ 2023-02-03 10:47  Frodo1124  阅读(30)  评论(0编辑  收藏  举报