235. Lowest Common Ancestor of a
2016-12-07 本文已影响9人
hyhchaos

Java,答案的想法很好,利用了二分树的特性
/**
* 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) {
while ((root.val - p.val) * (root.val - q.val) > 0)
root = q.val < root.val ? root.left : root.right;
return root;
}
}