zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    分析一:用两个辅助内存分别记录根节点到两个目标节点的路径。然后找出最后一个相同的节点。

            时间复杂度O(n), 空间复杂度一般O(lgn),最差空间复杂度O(n)

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (root == NULL || p == NULL || q == NULL)
                return NULL;
            
            vector<TreeNode*> path1;
            GetPath(root, p, path1);
            
            vector<TreeNode*> path2;
            GetPath(root, q, path2);
            
            return GetLastCommonNode(path1, path2);
        }
        
        TreeNode* GetLastCommonNode(const vector<TreeNode*>& path1, const vector<TreeNode*>& path2) {
            TreeNode* lastcommonnode = NULL;
            
            vector<TreeNode*>::const_iterator iter1 = path1.begin();
            vector<TreeNode*>::const_iterator iter2 = path2.begin();
            
            while (iter1 != path1.end() && iter2 != path2.end()) {
                if (*iter1 == *iter2) {
                    lastcommonnode = *iter1;
                }
                    
                iter1++;
                iter2++;
            }
            
            return lastcommonnode;
        }
        
        bool GetPath(TreeNode* root, TreeNode* p, vector<TreeNode*>& path) {
            path.push_back(root);
            
            if (root == p) return true;
            
            
            
            bool found = false;
            
            if (root->left != NULL) {
                found = GetPath(root->left, p, path);
            }
            
            if (!found && root->right != NULL)
                found = GetPath(root->right, p, path);
            
            if (!found)
                path.pop_back();
            
            return found;
        }
    };

    另一种方法:参考资料http://www.cnblogs.com/easonliu/p/4643873.html

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (root == NULL) return NULL;
            if (root == p || root == q) return root;
            TreeNode *L = lowestCommonAncestor(root->left, p, q);
            TreeNode *R = lowestCommonAncestor(root->right, p, q);
            if (L && R) return root;
            return L ? L : R;
        }
    };
  • 相关阅读:
    windows10家庭版安装docker踩坑解决记录
    sequelize Getters, Setters & Virtuals
    sequelize模型增删改查询(基础)Model Querying
    sequelize数据库模型关联文档详解
    Nginx配置实现下载文件
    Linux常用命令记录
    nodejs后台如何请求第三方接口request-promise简介及其废弃后的替代方案推荐got、axios
    新版本chrome浏览器(80版本以后)带来的跨域请求cookie丢失问题
    谷歌浏览器 Cookie 的 SameSite 属性 (转)
    JavaScript Image对象 整理
  • 原文地址:https://www.cnblogs.com/vincently/p/4774694.html
Copyright © 2011-2022 走看看