您的位置:首页 > 其它

Find the First Common Ancestor

2013-11-14 03:45 363 查看
class Tnode{
Tnode parent;
Tnode left;
Tnode right;
int val;
}

//if it has parent node
public Tnode ancestor(Tnode node1, Tnode node2) {
if(node1 == null || node2 == null) {
return null;
}

int height1 = getHeight(node1);
int height2 = getHeight(node2);
if(height1 > height2) {
node1 = balance(height1 - height2, node1);
}else if(height1 < height2) {
node2 = balance(height2 - height1, node2);
}

while(node1 != node2) {
node1 = node1.parent;
node2 = node2.parent;
}
return node1;
}

public int getHeight(Tnode node) {
int count = 1;
Tnode move = node;
while(move.parent != null) {
move = move.parent;
count++;
}
return count;
}
public Tnode balance(int a, Tnode node) {
for(int i = 0; i < a; i++) {
node = node.parent;
}
return node;
}

class Node{
Node left;
Node right;
}
//without parent
// we have three situations:
//first, they are all on the right, turn to right
//second, they are all on the left, turn to left;
//they are on different side, that is the point

//time complexity will be: O(n), because we will can help() method n times
public Node firstCommonAncestor(Node root, Node p, Node q) {
//judge if they are in the tree
if(!inTree(root, p) || !inTree(root, q)) return null;
return help(root, p, q);
}

public Node help(Node root, Node p, Node q) {
if(root == null) return null;
if(root == p || root == q) return root;

//judge if p, q are in the left
boolean pLeft = inTree(root.left, p);
boolean qLeft = inTree(root.left, q);

if(pLeft != qLeft) return root; //situation three, they are on different side
else return help((pLeft == true) ? root.left : root.right, p, q);
}

public boolean inTree(Node root, Node t) {
if(root == null) return false;
else if(t == root) return true;
return inTree(root.left, t) || inTree(root.right, t);
}

//optimization method
//use the hashset, then inorder to store, then preorder, find the first element between the two given elements.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: