1 //find the nearest public parent node in a tree2 Public classLCA {3 Static BooleanFlag[] =New Boolean[2];;4 5 Public StaticTreeNode Findlowestcommonancestor (TreeNode Head, TreeNode first, TreeNode second) {6 Travel (head, first, second);7 if(Flag[0] = =true&& flag[1] = =true)//two nodes are present8 returnLowestcommonancestor (head, first, second);9 Else Ten return NULL; One } A - Public Static voidTravel (TreeNode Head, TreeNode first, TreeNode second) { - if(Head = =NULL) the return; - - if(Head.value = =first.value) -Flag[0] =true; + if(Head.value = =second.value) -FLAG[1] =true; + Travel (Head.left, first, second); A Travel (Head.right, first, second); at } - - Public StaticTreeNode Lowestcommonancestor (TreeNode Head, TreeNode first, TreeNode second) { - if(Head = =NULL) - return NULL; - in //First Root traversal - if(Head.value = = First.value | | head.value = =second.value) to returnHead; +TreeNode left =Lowestcommonancestor (Head.left, first, second); -TreeNode right =Lowestcommonancestor (Head.right, first, second); the if(Left! =NULL) && (Right! =NULL)) { * returnhead; $ }Panax Notoginseng returnLeft! =NULL?Left:right; - } the + Public Static voidMain (string[] args) { ATreeNode Node1 =NewTreeNode (1); theTreeNode Node2 =NewTreeNode (2); +TreeNode Node3 =NewTreeNode (3); -TreeNode node4 =NewTreeNode (4); $TreeNode NODE5 =NewTreeNode (5); $TreeNode Node6 =NewTreeNode (6); -TreeNode Node7 =NewTreeNode (7); -Node1.left =Node2; theNode1.right =Node3; -Node2.left =Node4;WuyiNode2.right =Node5; theNode4.right =Node6; -TreeNode result = Findlowestcommonancestor (Node1, Node6, NODE5);//2 Wu //TreeNode result = Findlowestcommonancestor (Node1, Node1, node2);//1 - //TreeNode result = Findlowestcommonancestor (Node1, Node1, node7);//NULL About $SYSTEM.OUT.PRINTLN (Result! =NULL?result.value:result); - } - } - A classTreeNode { + TreeNode left; the TreeNode right; - intvalue; $ theTreeNode (intvalue) { the This. Value =value; the } the}
Find the nearest common parent node of a binary tree two node