您的位置:首页 > 其它

Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

2017-03-30 02:53 447 查看
// Recursive approach
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left, p, q);       // both p and q are smaller than root, LCA must in the left child tree
else if (root.val < p.val && root.val < q.val)
return lowestCommonAncestor(root.right, p, q);      // both p and q are larger than root, LCA must in the right child tree
else
return root;                                        // root is in the middle of p and q, so root is the LCA
}
}
// iterative approach
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
if (root.val > p.val && root.val > q.val)
root = root.left;                   // search the left child tree
else if (root.val < p.val && root.val < q.val)
root = root.right;                  // search the right child tree
else
break;
}
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: