235.二叉搜索数的最近公共祖先
方法:二次遍历
先遍历得到从根节点到p、根节点到q的路径,然后再遍历得到公共节点
/**
* 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) {
List<TreeNode> path_p = getPath(root,p);
List<TreeNode> path_q = getPath(root,q);
TreeNode ancetor = null;
for(int i = 0; i < path_p.size() && i < path_q.size();i++){
if(path_p.get(i) == path_q.get(i)){
ancetor = path_p.get(i);
} else{
break;
}
}
return ancetor;
}
//找到跟节点到目标节点的路径
public List<TreeNode> getPath(TreeNode root, TreeNode target){
List<TreeNode> path = new ArrayList<>();
TreeNode node = root;
while(node!=target){
path.add(node);
if(target.val < node.val){
node = node.left;
}else{
node = node.right;
}
}
path.add(node);
return path;
}
}
方法二:递归
/**
* 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 lowestCommonAncestor(root.right,p,q);
}
if(root.val > p.val && root.val > q.val){
return lowestCommonAncestor(root.left,p,q);
}
return root;
}
}