The sword refers to Offer 68-I. The nearest common ancestor of the binary search tree (recursive)

Title
Insert picture description here
because it is binary search tree can be determined phase interval
if the value of p and q are recursively right right of the current node
if the value of q and p are both at the left side of the current node left recursive
if Return the current node directly on both sides

    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;//p,q 在两侧
    }

Guess you like

Origin blog.csdn.net/qq_43434328/article/details/115302306