• 面试题19:二叉树镜像


    递归方法非常简单:

     1 void MirrorRecursively(BinaryTreeNode *pNode)
     2 {
     3     if((pNode == NULL) || (pNode->m_pLeft == NULL && pNode->m_pRight))
     4         return;
     5 
     6     BinaryTreeNode *pTemp = pNode->m_pLeft;
     7     pNode->m_pLeft = pNode->m_pRight;
     8     pNode->m_pRight = pTemp;
     9     
    10     if(pNode->m_pLeft)
    11         MirrorRecursively(pNode->m_pLeft);  
    12 
    13     if(pNode->m_pRight)
    14         MirrorRecursively(pNode->m_pRight); 
    15 }

    循环需要利用stack:

     1 void MirrorIteratively(BinaryTreeNode* pRoot)
     2 {
     3     if(pRoot == NULL)
     4         return;
     5 
     6     std::stack<BinaryTreeNode*> stackTreeNode;
     7     stackTreeNode.push(pRoot);
     8 
     9     while(stackTreeNode.size() > 0)
    10     {
    11         BinaryTreeNode *pNode = stackTreeNode.top();
    12         stackTreeNode.pop();
    13 
    14         BinaryTreeNode *pTemp = pNode->m_pLeft;
    15         pNode->m_pLeft = pNode->m_pRight;
    16         pNode->m_pRight = pTemp;
    17 
    18         if(pNode->m_pLeft)
    19             stackTreeNode.push(pNode->m_pLeft);
    20 
    21         if(pNode->m_pRight)
    22             stackTreeNode.push(pNode->m_pRight);
    23     }
    24 }
  • 相关阅读:
    多窗体
    滚动条
    个人信息调查
    登录页面
    蓝桥杯——放麦子
    java的BigDecimal
    蓝桥杯——判定字符的位置。
    输出日历
    蓝桥杯---简单的计算器
    蓝桥杯--Quadratic Equation
  • 原文地址:https://www.cnblogs.com/raichen/p/5646937.html
Copyright © 2020-2023  润新知