zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    Angular相关UI框架的安装
    Visual Studio Code 编辑器常用插件
    Groovy特性
    Notification(Android)消息推送机制
    Sublime SVN插件使用方法 PS:翻出来的旧笔记,现在Sublime和svn用的都不多了
    Python基本语法练习笔记(一)
    首篇博文占坑
    apache2修改用户和组
    如何修改script.bin/script.fex
    perl的INC设置
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4644132.html
Copyright © 2011-2022 走看看