您的位置:首页 > 其它

Lowest Common Ancestor of a Binary Search Tree

2016-07-11 15:21 363 查看
/**
* 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) {
return null;
}
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;
}
}

// public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//     if (root == null || root == p || root == q) {
//         return root;
//     }

//     TreeNode ln = lowestCommonAncestor(root.left, p, q);
//     TreeNode rn = lowestCommonAncestor(root.right, p, q);

//     if (ln != null && rn != null) {
//         return root;
//     }
//     if (ln != null) {
//         return ln;
//     }
//     if (rn != null) {
//         return rn;
//     }
//     return null;
// }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: