[leetCode]剑指 Offer 68

在这里插入图片描述

思路

从根节点开始遍历:

  • 如果当前节点大于p,q 那么p,q的最近公共节点在当前节点的左子树
  • 如果当前节点小于p,q 那么p,q的最近公共节点在当前节点的右子树
  • 如果当前节点的值不满足上述两条要求,那么说明当前节点就是「分岔点」。此时,pp 和 qq 要么在当前节点的不同的子树中,要么其中一个就是当前节点。

递归

class 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);
        if (root.val < p.val && root.val < q.val) 
            return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}

循环

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ancestor = root;
        while (true) {
            if (ancestor.val > p.val && ancestor.val > q.val)
                ancestor = ancestor.left;
            else if (ancestor.val < p.val && ancestor.val < q.val)
                ancestor = ancestor.right;
            else 
                break;
        }
        return ancestor;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13859921.html