235. Lowest Common Ancestor of a Binary Search Tree
一开始没发现是BST,以为是binary tree...草。。
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left,p,q);
else if(p.val > root.val && q.val > root.val) return lowestCommonAncestor(root.right,p,q);
else return root;
}
}
二刷?其实不知道是几刷。
用的递归,就3种情况,左边,右边,当前。
/**
* 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.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;
}
}
}
应该也可以迭代,试一下。
想多了,这不是BFS,DFS那种迭代递归的区别,这里迭代也很容易。。而且不需要额外的数据结构,省下了recursion里对于stack的空间消耗。
/**
* 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) {
TreeNode temp = root;
while (temp != null) {
if (temp.val < p.val && temp.val < q.val) {
temp = temp.right;
} else if (temp.val > p.val && temp.val > q.val) {
temp = temp.left;
} else {
return temp;
}
}
return temp;
}
}
Time: iteratively O(n) recursively O(n) as well
Space: Iteratively better than recursively..