Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has 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 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
直接用上一题的丑陋解法居然也能过。
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} root 10 * @param {TreeNode} p 11 * @param {TreeNode} q 12 * @return {TreeNode} 13 */ 14 var lowestCommonAncestor = function(root, p, q) { 15 var target = [], res, isFound = false; 16 target.push(p.val); 17 target.push(q.val); 18 findLCA(root); 19 return res; 20 21 function findLCA(node){ 22 if(isFound){ 23 return []; 24 } 25 26 var candidates = []; 27 if(node.left !== null){ 28 var left = findLCA(node.left); 29 left = compareVal(left); 30 if(left === true){ 31 res = node.left; 32 isFound = true; 33 return []; 34 }else if(left.length === 1){ 35 candidates= left; 36 } 37 } 38 39 if(node.right !== null && !isFound){ 40 var right = findLCA(node.right); 41 if(right && right.length === 1){ 42 candidates.push(right[0]); 43 } 44 right = compareVal(candidates); 45 if(right === true){ 46 res = node; 47 isFound = true; 48 return []; 49 }else if(right.length === 1){ 50 candidates = right; 51 } 52 } 53 54 if(!isFound){ 55 candidates.push(node.val); 56 var curr = compareVal(candidates); 57 if(curr === true){ 58 res = node; 59 isFound = true; 60 return []; 61 } 62 return curr; 63 } 64 65 } 66 function compareVal(a, b){ 67 if(typeof a === "object"){ 68 if(a.length === 2){ 69 b = a[1]; 70 a = a[0]; 71 }else if(a.length === 1){ 72 a = a[0]; 73 } 74 } 75 var index1 = target.indexOf(a); 76 var index2 = target.indexOf(b); 77 if(index1 !== -1 && index2 !== -1 && (index1 !== index2 || a === b)){ 78 return true; 79 }else{ 80 if(index1 !== -1){ 81 return [a]; 82 }else if(index2 !== -1){ 83 return [b]; 84 } 85 } 86 return []; 87 } 88 };
[LeetCode][JavaScript]Lowest Common Ancestor of a Binary Tree
原文:http://www.cnblogs.com/Liok3187/p/4644132.html