zoukankan      html  css  js  c++  java
  • 236. Lowest Common Ancestor of a Binary Tree

    236. 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.

    解析

    思路:从根节点开始遍历,如果node1和node2中的任一个和root匹配,那么root就是最低公共祖先。 如果都不匹配,则分别递归左、右子树,如果有一个 节点出现在左子树,并且另一个节点出现在右子树,则root就是最低公共祖先.  如果两个节点都出现在左子树,则说明最低公共祖先在左子树中,否则在右子树。感觉很奇妙。引申的问题

    • 如果给定的不是二叉树,而是二叉搜索树呢?会比较简单一点,如果是带有指向父节点的指针的树,可以转化为两个链表求交汇点的问题。
    class Solution_236 {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
            if (root==NULL||root==q||root==p)
            {
                return root;
            }
    
            TreeNode* left = lowestCommonAncestor(root->left, p, q);
            TreeNode* right = lowestCommonAncestor(root->right, p, q);
    
            if (left!=NULL&&right!=NULL)
            {
                return root;
            }
    
            return left == NULL ? right : left;
        }
    };
  • 相关阅读:
    c#中==和equals的比较
    原型指向改变如何添加方法和访问
    把随机数对象暴露给window成为全局变量
    内置对象Array的原型对象中添加方法
    构造函数可以实例化对象
    原型
    无刷新评论
    大量字符串拼接案例
    元素隐藏占位与不占位
    导航栏切换效果案例
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8953951.html
Copyright © 2011-2022 走看看