[LeetCode][JavaScript]Lowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree

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/

 

 

 


 

 

比较难以描述...

我的理解是把目标的节点向上"冒泡",拿这个做例子:the lowest common ancestor (LCA) of nodes 5 and 1 is 3

从下往上看,6这个节点往上一层返回null,因为这个节点本身,它的左子树和右子树都不包含1和5。

同理7,4,2返回null,

5这个节点左右子树不包含1和5,但它自身是5,返回5,

同理以1为根节点的树返回1,

以1为根节点的树发现左右都不为null,说明找到了。

以上是一种情况,还有一种情况就是一旦发现目前的节点等于p或者q,就可以直接返回,因为默认输入是正确的。

 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     if(root === null || root === p || root === q){
16         return root;
17     }
18     var left = lowestCommonAncestor(root.left, p, q);
19     var right = lowestCommonAncestor(root.right, p, q);
20     return left !== null && right !== null ? root : (left !== null ? left : right);
21 }

 

posted @ 2015-07-13 22:33  `Liok  阅读(270)  评论(0编辑  收藏  举报