Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of the Given nodes in the tree.
According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allow a node to be a descendant of itself). "
_______3______ / ___5__ ___1__ / \ / 6 _2 0 8 / 7 4
For example, the lowest common ancestor (LCA) of nodes and are 5 1 3 . Another example is LCA of nodes 5 4 5 and are, since a node can be a descendant of itself according to the L CA definition.
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
The ugly solution of using the previous question can be too.
Http://www.cnblogs.com/Liok3187/p/4641389.html
1 /**2 * Definition for a binary tree node.3 * Function TreeNode (val) {4 * This.val = val;5 * This.left = This.right = null;6 * }7 */8 /**9 * @param {TreeNode} rootTen * @param {TreeNode} p One * @param {TreeNode} q A * @return {TreeNode} - */ - varLowestcommonancestor =function(Root, p, q) { the vartarget = [], res, isfound =false; - Target.push (p.val); - Target.push (q.val); - Findlca (root); + returnRes; - + functionFINDLCA (node) { A if(isfound) { at return []; - } - - varCandidates = []; - if(Node.left!==NULL){ - varleft =Findlca (node.left); inleft =Compareval (left); - if(left = = =true){ tores =Node.left; +Isfound =true; - return []; the}Else if(Left.length = = 1){ *candidates=Left ; $ }Panax Notoginseng } - the if(Node.right!==NULL&&!isfound) { + varright =Findlca (node.right); A if(right && right.length = = = 1){ theCandidates.push (right[0]); + } -right =Compareval (candidates); $ if(right = = =true){ $res =node; -Isfound =true; - return []; the}Else if(Right.length = = 1){ -Candidates =Right ;Wuyi } the } - Wu if(!isfound) { - Candidates.push (node.val); About varCurr =Compareval (candidates); $ if(Curr = = =true){ -res =node; -Isfound =true; - return []; A } + returnCurr; the } - $ } the functionCompareval (A, b) { the if(typeofA = = = "Object"){ the if(A.length = = 2){ theb = a[1]; -A = A[0]; in}Else if(A.length = = 1){ theA = A[0]; the } About } the varIndex1 =Target.indexof (a); the varIndex2 =Target.indexof (b); the if(Index1!==-1 && index2!==-1 && (index1!== Index2 | | a = = =b)) { + return true; -}Else{ the if(Index1!==-1){Bayi return[a]; the}Else if(Index2!==-1){ the return[b]; - } - } the return []; the } the};
[Leetcode] [JavaScript] Lowest Common Ancestor of a Binary Tree