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.
相关文章推荐
- python环境搭建和开发工具的配置【转】
- 在C语言环境下使用google protobuf
- sqlmap注入常见用法一条龙 【转】
- Java Memory Basic
- Django Meta小节(二) 之ModelForm
- jquery总结
- java Hotspot 内存管理白皮书(中文翻译)
- Cantor展开式
- Ubuntu 下配置 Eclipse + Tomcat7 开发环境
- 在C语言环境下使用google protobuf
- 工作三个月总结2
- hook resize
- 《高可用MySQL——构建健壮的数据中心》读书笔记之二
- VS2110。VC++编译错误"error LNK2005: 已经在 XXX.obj 中定义的问题"
- Find Median With Two heaps
- keepalived
- 关于 C# 中接口的一些小结
- LeetCode 之 Minimum Depth of Binary Tree
- 工作三个月总结1
- MFC学习记录--从win32程序到MFC