Topic:
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.
Ideas:
The common ancestor c of Node A and Node B must be satisfied: A and B appear on the left and right subtree of C, or a A and a.
/** Definition for a binary tree node. * Function TreeNode (val) {* This.val = val; * This.left = This.right = Null * } *//** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} Q * @return {TreeNode}*/varLowestcommonancestor =function(Root, p, q) {if(root==NULL){ return; } if(root==p| | root==q) { returnRoot; } varL=Lowestcommonancestor (ROOT.LEFT,P,Q); varR=Lowestcommonancestor (ROOT.RIGHT,P,Q); if(l&&R) { returnRoot; }Else{ returnL?l:r; } };
"Tree" Lowest Common Ancestor of a Binary tree (recursive)