This problem can be solved by using the solution of 236. Lowest Common Ancestor of a Binary Tree.

While the tree here is a binary search tree, so the tree is sorted, we can have a simpler solution:

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root.val>p.val&&root.val>q.val){
            return lowestCommonAncestor(root.left, p, q);
        }else if(root.val<p.val&&root.val<q.val)
            return lowestCommonAncestor(root.right, p, q);
        return root;
    }

 

posted on 2022-02-08 09:44  阳光明媚的菲越  阅读(31)  评论(0编辑  收藏  举报