【DFS】LeetCode 235. 二叉搜索树的最近公共祖先

题目链接

235. 二叉搜索树的最近公共祖先

思路

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

代码

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 12:11  Frodo1124  阅读(14)  评论(0编辑  收藏  举报