你的位置:首页 > Java教程

[Java教程]235. 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) {

if(root==null||p==null||q==null)
return root;

TreeNode t=root;

if(Math.max(p.val,q.val)<root.val&&root.left!=null)
return lowestCommonAncestor(root.left,p,q);
else if(Math.min(p.val,q.val)>root.val&&root.right!=null)
return lowestCommonAncestor(root.right,p,q);
else if(Math.min(p.val,q.val)<=root.val&&Math.max(p.val,q.val)>=root.val)
return root;

return root;
}

}