两链表的第一个公共结点->二叉树两结点的最近共同父结点

本文探讨了链表的第一个公共节点及二叉树中两个节点的最低共同父节点问题,提供了多种解决方法并分析了各自的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载至http://zhedahht.blog.163.com/

题目:两个单向链表,找出它们的第一个公共结点。

链表的结点定义为:

struct ListNode

{

      int         m_nKey;

      ListNode*   m_pNext;

};

分析:这是一道微软的面试题。微软非常喜欢与链表相关的题目,因此在微软的面试题中,链表出现的概率相当高。

如果两个单向链表有公共的结点,也就是说两个链表从某一结点开始,它们的m_pNext都指向同一个结点。但由于是单向链表的结点,每个结点只有一个m_pNext,因此从第一个公共结点开始,之后它们所有结点都是重合的,不可能再出现分叉。所以,两个有公共结点而部分重合的链表,拓扑形状看起来像一个Y,而不可能像X

看到这个题目,第一反应就是蛮力法:在第一链表上顺序遍历每个结点。每遍历一个结点的时候,在第二个链表上顺序遍历每个结点。如果此时两个链表上的结点是一样的,说明此时两个链表重合,于是找到了它们的公共结点。如果第一个链表的长度为m,第二个链表的长度为n,显然,该方法的时间复杂度为O(mn)

接下来我们试着去寻找一个线性时间复杂度的算法。我们先把问题简化:如何判断两个单向链表有没有公共结点?前面已经提到,如果两个链表有一个公共结点,那么该公共结点之后的所有结点都是重合的。那么,它们的最后一个结点必然是重合的。因此,我们判断两个链表是不是有重合的部分,只要分别遍历两个链表到最后一个结点。如果两个尾结点是一样的,说明它们用重合;否则两个链表没有公共的结点。

在上面的思路中,顺序遍历两个链表到尾结点的时候,我们不能保证在两个链表上同时到达尾结点。这是因为两个链表不一定长度一样。但如果假设一个链表比另一个长l个结点,我们先在长的链表上遍历l个结点,之后再同步遍历,这个时候我们就能保证同时到达最后一个结点了。由于两个链表从第一个公共结点考试到链表的尾结点,这一部分是重合的。因此,它们肯定也是同时到达第一公共结点的。于是在遍历中,第一个相同的结点就是第一个公共的结点。

在这个思路中,我们先要分别遍历两个链表得到它们的长度,并求出两个长度之差。在长的链表上先遍历若干次之后,再同步遍历两个链表,知道找到相同的结点,或者一直到链表结束。此时,如果第一个链表的长度为m,第二个链表的长度为n,该方法的时间复杂度为O(m+n)

基于这个思路,我们不难写出如下的代码:

///////////////////////////////////////////////////////////////////////

// Find the first common node in the list with head pHead1 and

// the list with head pHead2

// Input: pHead1 - the head of the first list

//        pHead2 - the head of the second list

// Return: the first common node in two list. If there is no common

//         nodes, return NULL

///////////////////////////////////////////////////////////////////////

ListNodeFindFirstCommonNodeListNode *pHead1ListNode *pHead2)

{

      // Get the length of two lists

      unsigned int nLength1 = ListLength(pHead1);

      unsigned int nLength2 = ListLength(pHead2);

      int nLengthDif = nLength1 - nLength2;

 

      // Get the longer list

      ListNode *pListHeadLong = pHead1;

      ListNode *pListHeadShort = pHead2;

      if(nLength2 > nLength1)

      {

            pListHeadLong = pHead2;

            pListHeadShort = pHead1;

            nLengthDif = nLength2 - nLength1;

      }

 

      // Move on the longer list

      for(int i = 0; i < nLengthDif; ++ i)

            pListHeadLong = pListHeadLong->m_pNext;

 

      // Move on both lists

      while((pListHeadLong != NULL) &&

            (pListHeadShort != NULL) &&

            (pListHeadLong != pListHeadShort))

      {

            pListHeadLong = pListHeadLong->m_pNext;

            pListHeadShort = pListHeadShort->m_pNext;

      }

 

      // Get the first common node in two lists

      ListNode *pFisrtCommonNode = NULL;

      if(pListHeadLong == pListHeadShort)

            pFisrtCommonNode = pListHeadLong;

 

      return pFisrtCommonNode;

}

 

///////////////////////////////////////////////////////////////////////

// Get the length of list with head pHead

// Input: pHead - the head of list

// Return: the length of list

///////////////////////////////////////////////////////////////////////

unsigned int ListLength(ListNodepHead)

{

      unsigned int nLength = 0;

      ListNodepNode = pHead;

      while(pNode != NULL)

      {

            ++ nLength;

            pNode = pNode->m_pNext;

      }

 

      return nLength;

}

题目:二叉树的结点定义如下:

struct TreeNode

{

    int m_nvalue;

    TreeNode* m_pLeft;

    TreeNode* m_pRight;

};

输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。

分析:求数中两个结点的最低共同结点是面试中经常出现的一个问题。这个问题至少有两个变种。

第一变种是二叉树是一种特殊的二叉树:查找二叉树。也就是树是排序过的,位于左子树上的结点都比父结点小,而位于右子树的结点都比父结点大。我们只需要从根结点开始和两个结点进行比较。如果当前结点的值比两个结点都大,则最低的共同父结点一定在当前结点的左子树中。如果当前结点的值比两个结点都小,则最低的共同父结点一定在当前结点的右子树中。

第二个变种是树不一定是二叉树,每个结点都有一个指针指向它的父结点。于是我们可以从任何一个结点出发,得到一个到达树根结点的单向链表。因此这个问题转换为两个单向链表的第一个公共结点。我们在前面已经讨论了这个问题。

现在我们回到这个问题本身。所谓共同的父结点,就是两个结点都出现在这个结点的子树中。因此我们可以定义一函数,来判断一个结点的子树中是不是包含了另外一个结点。这不是件很难的事,我们可以用递归的方法来实现:

/////////////////////////////////////////////////////////////////////////////////

// If the tree with head pHead has a node pNode, return true.

// Otherwise return false.

/////////////////////////////////////////////////////////////////////////////////

bool HasNode(TreeNode* pHead, TreeNode* pNode)

{

    if(pHead == pNode)

        return true;

 

    bool has = false;

 

    if(pHead->m_pLeft != NULL)

        has = HasNode(pHead->m_pLeft, pNode);

 

    if(!has && pHead->m_pRight != NULL)

        has = HasNode(pHead->m_pRight, pNode);

 

    return has;

}

我们可以从根结点开始,判断以当前结点为根的树中左右子树是不是包含我们要找的两个结点。如果两个结点都出现在它的左子树中,那最低的共同父结点也出现在它的左子树中。如果两个结点都出现在它的右子树中,那最低的共同父结点也出现在它的右子树中。如果两个结点一个出现在左子树中,一个出现在右子树中,那当前的结点就是最低的共同父结点。基于这个思路,我们可以写出如下代码:

/////////////////////////////////////////////////////////////////////////////////

// Find the last parent of pNode1 and pNode2 in a tree with head pHead

/////////////////////////////////////////////////////////////////////////////////

TreeNode* LastCommonParent_1(TreeNode* pHead, TreeNode* pNode1, TreeNode* pNode2)

{

    if(pHead == NULL || pNode1 == NULL || pNode2 == NULL)

        return NULL;

 

    // check whether left child has pNode1 and pNode2

    bool leftHasNode1 = false;

    bool leftHasNode2 = false;

    if(pHead->m_pLeft != NULL)

    {

        leftHasNode1 = HasNode(pHead->m_pLeft, pNode1);

        leftHasNode2 = HasNode(pHead->m_pLeft, pNode2);

    }

 

    if(leftHasNode1 && leftHasNode2)

    {

        if(pHead->m_pLeft == pNode1 || pHead->m_pLeft == pNode2)

            return pHead;

 

        return LastCommonParent_1(pHead->m_pLeft, pNode1, pNode2);

    }

 

    // check whether right child has pNode1 and pNode2

    bool rightHasNode1 = false;

    bool rightHasNode2 = false;

    if(pHead->m_pRight != NULL)

    {

        if(!leftHasNode1)

            rightHasNode1 = HasNode(pHead->m_pRight, pNode1);

        if(!leftHasNode2)

            rightHasNode2 = HasNode(pHead->m_pRight, pNode2);

    }

 

    if(rightHasNode1 && rightHasNode2)

    {

        if(pHead->m_pRight == pNode1 || pHead->m_pRight == pNode2)

            return pHead;

 

        return LastCommonParent_1(pHead->m_pRight, pNode1, pNode2);

    }

 

    if((leftHasNode1 && rightHasNode2)

        || (leftHasNode2 && rightHasNode1))

        return pHead;

 

    return NULL;

}

接着我们来分析一下这个方法的效率。函数HasNode的本质就是遍历一棵树,其时间复杂度是O(n)n是树中结点的数目)。由于我们根结点开始,要对每个结点调用函数HasNode。因此总的时间复杂度是O(n2)

我们仔细分析上述代码,不难发现我们判断以一个结点为根的树是否含有某个结点时,需要遍历树的每个结点。接下来我们判断左子结点或者右结点为根的树中是否含有要找结点,仍然需要遍历。第二次遍历的操作其实在前面的第一次遍历都做过了。由于存在重复的遍历,本方法在时间效率上肯定不是最好的。

前面我们提过如果结点中有一个指向父结点的指针,我们可以把问题转化为求两个链表的共同结点。现在我们可以想办法得到这个链表。我们分析如何得到一条中根结点开始的路径。

题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。

例如输入整数22和如下二元树

                                10
                                           /   \
                                          5     12
                                        /   \   
                                      4     7 

则打印出两条路径:10, 1210, 5, 7

二元树结点的数据结构定义为:

struct BinaryTreeNode // a node in the binary tree
{
      int              m_nValue; // value of node
      BinaryTreeNode  *m_pLeft;  // left child of node
      BinaryTreeNode  *m_pRight; // right child of node
};

分析:这是百度的一道笔试题,考查对树这种基本数据结构以及递归函数的理解。

当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点。因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。我们不难看出保存路径的数据结构实际上是一个栈结构,因为路径要与递归调用状态一致,而递归调用本质就是一个压栈和出栈的过程。

参考代码:

///////////////////////////////////////////////////////////////////////
// Find paths whose sum equal to expected sum
///////////////////////////////////////////////////////////////////////
void FindPath
(
      BinaryTreeNode*   pTreeNode,    // a node of binary tree
      int               expectedSum,  // the expected sum
      std::vector<int>& path,         // a path from root to current node
      int&              currentSum    // the sum of path
)
{
      if(!pTreeNode)
            return;

      currentSum += pTreeNode->m_nValue;
      path.push_back(pTreeNode->m_nValue);

      // if the node is a leaf, and the sum is same as pre-defined, 
      // the path is what we want. print the path
      bool isLeaf = (!pTreeNode->m_pLeft && !pTreeNode->m_pRight);
      if(currentSum == expectedSum && isLeaf)
      {    
           std::vector<int>::iterator iter = path.begin();
           for(; iter != path.end(); ++ iter)
                 std::cout << *iter << '\t';
           std::cout << std::endl;
      }

      // if the node is not a leaf, goto its children
      if(pTreeNode->m_pLeft)
            FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);
      if(pTreeNode->m_pRight)
            FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);

      // when we finish visiting a node and return to its parent node,
      // we should delete this node from the path and 
      // minus the node's value from the current sum
      currentSum -= pTreeNode->m_nValue;
      path.pop_back();
} 

我们在这里稍作变化即可:

/////////////////////////////////////////////////////////////////////////////////

// Get the path form pHead and pNode in a tree with head pHead

/////////////////////////////////////////////////////////////////////////////////

bool GetNodePath(TreeNode* pHead, TreeNode* pNode, std::list<TreeNode*>& path)

{

    if(pHead == pNode)

        return true;

 

    path.push_back(pHead);

 

    bool found = false;

    if(pHead->m_pLeft != NULL)

        found = GetNodePath(pHead->m_pLeft, pNode, path);

    if(!found && pHead->m_pRight)

        found = GetNodePath(pHead->m_pRight, pNode, path);

 

    if(!found)

        path.pop_back();

 

    return found;

}

由于这个路径是从跟结点开始的。最低的共同父结点就是路径中的最后一个共同结点:

/////////////////////////////////////////////////////////////////////////////////

// Get the last common Node in two lists: path1 and path2

/////////////////////////////////////////////////////////////////////////////////

TreeNode* LastCommonNode

(

    const std::list<TreeNode*>& path1,

    const std::list<TreeNode*>& path2

)

{

    std::list<TreeNode*>::const_iterator iterator1 = path1.begin();

    std::list<TreeNode*>::const_iterator iterator2 = path2.begin();

   

    TreeNode* pLast = NULL;

 

    while(iterator1 != path1.end() && iterator2 != path2.end())

    {

        if(*iterator1 == *iterator2)

            pLast = *iterator1;

 

        iterator1++;

        iterator2++;

    }

 

    return pLast;

}

有了前面两个子函数之后,求两个结点的最低共同父结点就很容易了。我们先求出从根结点出发到两个结点的两条路径,再求出两条路径的最后一个共同结点。代码如下:

/////////////////////////////////////////////////////////////////////////////////

// Find the last parent of pNode1 and pNode2 in a tree with head pHead

/////////////////////////////////////////////////////////////////////////////////

TreeNode* LastCommonParent_2(TreeNode* pHead, TreeNode* pNode1, TreeNode* pNode2)

{

    if(pHead == NULL || pNode1 == NULL || pNode2 == NULL)

        return NULL;

 

    std::list<TreeNode*> path1;

    GetNodePath(pHead, pNode1, path1);

 

    std::list<TreeNode*> path2;

    GetNodePath(pHead, pNode2, path2);

 

    return LastCommonNode(path1, path2);

}

这种思路的时间复杂度是O(n),时间效率要比第一种方法好很多。但同时我们也要注意到,这种思路需要两个链表来保存路径,空间效率比不上第一个方法。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值