
方法1: 和235一个思路,但是由于这题不是BST,所以我们需要一个额外的函数来判断两个点所在的位置。时间复杂感觉是n的平方,空间复杂logn。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val == p.val || root.val == q.val) return root;
while(root != null){
int locationP = sameTree(root,p);
int locationQ = sameTree(root,q);
if(locationP == locationQ && locationQ == -1){
root = root.left;
}else if(locationP == locationQ && locationQ== 1){
root = root.right;
}else{
return root;
}
}
return null;
}
// left -1, right 1
private int sameTree(TreeNode root, TreeNode node){
TreeNode left = root.left;
TreeNode right = root.right;
if(left != null && left.val == node.val) return -1;
if(right != null && right.val == node.val) return 1;
int res1 = left == null ? 0 : sameTree(left,node);
int res2 = right == null ? 0 : sameTree(right,node);
if(res1 != 0) return -1;
else if(res2 != 0) return 1;
else return 0;
}
}
方法2: dfs manner。是一个用recursion实现的dfs。自己看lc官方解答1,写的挺好的。时间复杂logn,空间复杂logn。
class Solution {
private TreeNode ans;
public Solution() {
// Variable to store LCA node.
this.ans = null;
}
private boolean recurseTree(TreeNode currentNode, TreeNode p, TreeNode q) {
// If reached the end of a branch, return false.
if (currentNode == null) {
return false;
}
// Left Recursion. If left recursion returns true, set left = 1 else 0
int left = this.recurseTree(currentNode.left, p, q) ? 1 : 0;
// Right Recursion
int right = this.recurseTree(currentNode.right, p, q) ? 1 : 0;
// If the current node is one of p or q
int mid = (currentNode == p || currentNode == q) ? 1 : 0;
// If any two of the flags left, right or mid become True
if (mid + left + right >= 2) {
this.ans = currentNode;
}
// Return true if any one of the three bool values is True.
return (mid + left + right > 0);
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Traverse the tree
this.recurseTree(root, p, q);
return this.ans;
}
}
总结:
- 无
253

被折叠的 条评论
为什么被折叠?



