您的位置:首页 > 其它

二叉搜索数求最近公共祖先

2016-05-22 19:31 375 查看
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}

public class Solution {
//递归解法
public TreeNode lowestCommonAncestor1(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;
}
}
//非递归,先求路径
LinkedList<TreeNode> getPath(TreeNode root, TreeNode node){
LinkedList<TreeNode> path = new LinkedList<>();
path.push(root);
if(node == root){
return path;
}

TreeNode temp = root;
while (temp != null){
if(node.val < temp.val){
temp = temp.left;
}else if(node.val > temp.val){
temp = temp.right;
}
path.push(temp);
if(node.val == temp.val){
break;
}
}
return path;
}

public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
LinkedList<TreeNode> pPath = getPath(root, p);
LinkedList<TreeNode> qPath = getPath(root, q);
int i = 0;
int dif = pPath.size() - qPath.size();
if (dif > 0){
i = dif;
while (i-- > 0){
pPath.pop();
}
}else if(dif < 0){
i = -dif;
while (i-- > 0){
qPath.pop();
}
}

TreeNode pNode,qNode;
while (!pPath.isEmpty()){
pNode = pPath.poll();
qNode = qPath.poll();
if(pNode.val == qNode.val){
return pNode;
}
}

return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉搜索树 LCA