经典题目:最近公共祖先

二叉树最近公共祖先:236. 二叉树的最近公共祖先 - 力扣(LeetCode)

思路:经典题目:最近公共祖先_第1张图片

 

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);
        if(left != null && right != null){
            return root;
        }
        if(left != null ){
            return left;
        }
        return right;
    }
}

 二叉搜索树最近公共祖先:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)

与二叉搜索树的搜索类似,可参考之前的博客:(126条消息) 700. 二叉搜索树中的搜索_失业的博客-CSDN博客

 

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //使得p>=q
        TreeNode temp;
        if(p.val= q.val){
                return root;
            }
            if(root.val > p.val){
                root = root.left;
                continue;
            }
            root = root.right;
        }
        return root;
    }
}

下面是大佬的做法,省去了q和p大小比较的片段,只要求最终x在p q中间即可。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int x = root.val;
        if (p.val < x && q.val < x)
            return lowestCommonAncestor(root.left, p, q);
        if (p.val > x && q.val > x)
            return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}

你可能感兴趣的:(算法,leetcode,职场和发展)