235. Lowest Common Ancestor of a Binary Search Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
解题思路:
首先得到p和q的最大值和最小值,然后判断是否最大值小于root.val和最小值大于root.val

代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
int max = p.val > q.val ? p.val : q.val;
int min = p.val > q.val ? q.val : p.val;
if(max < root.val){
return lowestCommonAncestor(root.left, p, q);
} else if(min > root.val){
return lowestCommonAncestor(root.right, p, q);
} else
return root;
}
}

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