zoukankan      html  css  js  c++  java
  • 面试题50 树中两个结点的最低公共祖先

     1 bool GetNodePath(TreeNode *pRoot, TreeNode *pNode, list<TreeNode *>&path)
     2 {
     3     if (pRoot == pNode)
     4         return true;
     5     path.push_back(pRoot);
     6     bool found = false;
     7     vector<TreeNode *>::iterator i = pRoot->m_vChildren.begin();
     8     while (!found && i < pRoot->m_vChildren.end())
     9     {
    10         found = GetNodePath(*i, pNode, path);
    11         ++i;
    12     }
    13     if (!found)
    14         path.pop_back();
    15     return found;
    16 }
    17 
    18 TreeNode *GetLastCommonNode(const list<TreeNode*>& path1, const list<TreeNode*>& path2)
    19 {
    20     list<TreeNode*>::const_iterator iterator1 = path1.begin();
    21     list<TreeNode*>::const_iterator iterator2 = path2.begin();
    22 
    23     TreeNode* pLast = NULL;
    24 
    25     while (iterator1 != path1.end() && iterator2 != path2.end())
    26     {
    27         if (*iterator1 == *iterator2)
    28             pLast = *iterator1;
    29         iterator1++;
    30         iterator2++;
    31     }
    32     return pLast;
    33 }
    34 
    35 TreeNode* GetLastCommonParent(TreeNode* pRoot, TreeNode* pNode1, TreeNode* pNode2)
    36 {
    37     if (pRoot == NULL || pNode1 == NULL || pNode2 == NULL)
    38         return NULL;
    39     list<TreeNode*> path1;
    40     GetNodePath(pRoot, pNode1, path1);
    41 
    42     list<TreddNode*> path2;
    43     GetNodePath(pRoot, pNode1, pNode2);
    44 
    45     return GetLastCommonNode(path1, path2);
    46 }
  • 相关阅读:
    图解SSH隧道功能
    su和sudo命令的用法
    Linux下下载百度网盘资料
    WPS Office 2019 for Linux来了
    Linux下的录屏软件Kazam
    用hdparm获取硬盘参数
    百度,你能不能有点节操?
    locate的基本用法
    Java class不分32位和64位
    Web站点抓取工具webhttrack
  • 原文地址:https://www.cnblogs.com/wanderingzj/p/5374421.html
Copyright © 2011-2022 走看看