235. Lowest Common Ancestor of a Binary Search Tree

 

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

找最小共同祖先,如3和5的最小共同祖先是4, 0和7的最小共同祖先是6

//看p和q是否同时大于或者同时小于root

Solution 1

class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        while ((root.val - p.val) * (root.val - q.val) > 0) {

            root = root.val > p.val ? root.left : root.right;

        }

        return root;

    }

}

Solution 2://递归

public 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);

        } else if (root.val < p.val && root.val < q.val) {

            return lowestCommonAncestor(root.right, p, q);

        } else {

            return root;

        }

    }

}

 

posted @ 2019-03-15 15:40  MarkLeeBYR  阅读(105)  评论(0)    收藏  举报