larscheng / algo

0 stars 0 forks source link

【Check 57】2024-04-20 - 236. 二叉树的最近公共祖先 #159

Open larscheng opened 5 months ago

larscheng commented 5 months ago

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

larscheng commented 5 months ago

思路

先序遍历,根左右,如果q、p等于root,直接返回root

代码


class Solution {

    //O(n)/O(n)
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == q || root == p) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }
        return root;
    }
}

复杂度