fwnx- find the common ancestor in a tree

来源:互联网 发布:php substr函数 编辑:程序博客网 时间:2024/05/17 06:09


1 if the nodes are in the left tree then find the common ancestor in the left tree

2 if the nodes are in the right tree then find the common ancestor in the right tree

3 if the nodes are in different tree of the node root; then return the root; 


-- so easy but absolutely correct statement;


boolean covers(Node root,Node test){// is test is the child of root ?if(root == null) return false;if(root == test) return true;return covers(root.left_child,test) || covers(root.right_child,test);}Node findCommoAn(Node root,Node nd1,Node nd2){if(covers(root.right_child,nd1) && covers(root.right_child,nd2)){// if nd1 and nd2 both at the right tree;  returnfindCommoAn(root.right_child,nd1,nd2);}// if nd1 and nd2 both at the left tree if(covers(root.left_child,nd1) && covers(root.left_child,nd2)){return findCommoAn(root.left_child,nd1,nd2);}return root;}


0 0
原创粉丝点击