Lowest Common Ancestor of a Binary Search Tree

题目链接

思路:
就是运用二分查找。每查找一步比较一下分支的走向。如果两个节点的分支走向不同,那么现在这个节点就是最低的公共祖先,如果相同,那么接下来的查找还可能相同,程序要继续运行。

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode pointerP=root;
        TreeNode pointerQ=root;
        while(true)
        {
            pointerP=findPath(root,p);
            pointerQ=findPath(root,q);
            if(pointerP!=pointerQ)
            {
                return root;
            }
            else
            {
                root=pointerP;
            }

        }
    }

    public TreeNode findPath(TreeNode root,TreeNode target)
    {
        if(root.val<target.val)
        {
            return root.right;
        }
        else if(root.val>target.val)
        {
            return root.left;
        }
        else
        {
            return root;
        }
    }
}

你可能感兴趣的:(Lowest Common Ancestor of a Binary Search Tree)