zoukankan      html  css  js  c++  java
  • 算法题22 树的镜像

    题目

      完成一个函数,输入一个二叉树,构建它的镜像二叉树

    分析

      这个题目最直观的解法是递归,交换左右子树(即交换左右孩子)。

    代码

     1 void MirrorTree(TreeNode* root)
     2 {
     3     if (!root)
     4         throw std::exception("Invalid input.");
     5 
     6     //swap the left and right subtree
     7     TreeNode* tmp=root->pLeft;
     8     root->pLeft=root->pRight;
     9     root->pRight=tmp;
    10 
    11     //recursion
    12     if (root->pLeft)
    13         MirrorTree(root->pLeft);
    14     if (root->pRight)
    15         MirrorTree(root->pRight);
    16 
    17 }

      也可以用非递归的方式去解决,借鉴分层遍历的思路,借助一个双向队列,分层遍历这个二叉树,在遍历的过程中交换每个节点的左右孩子即可

     1 void MirrorTree1(TreeNode* root)
     2 {
     3     if (!root)
     4         throw std::exception("Invalid input.");
     5 
     6     deque<TreeNode*> dq;
     7     TreeNode* node;
     8     dq.push_back(root);
     9     while (dq.size()>0)
    10     {
    11         node=dq.front();
    12         
    13         if (node->pLeft==NULL&&node->pRight==NULL)
    14         {
    15             dq.pop_front();
    16             continue;
    17         }
    18         TreeNode* tmp=node->pLeft;
    19         node->pLeft=node->pRight;
    20         node->pRight=tmp;
    21 
    22         if(node->pLeft)
    23             dq.push_back(node->pLeft);
    24         if(node->pRight)
    25             dq.push_back(node->pRight);
    26         dq.pop_front();
    27     }
    28 }
  • 相关阅读:
    ASP.NET面试题(二)
    iBatis.Net系列(四) iBatisNet API基础
    ibatisnet系列(一) 总览
    iBatisnet系列(二) 配置运行环境和日志处理
    HDU 1575 Tr A (矩阵乘法)
    HDU 连连看
    1504: ZZ的橱柜 (优先队列)
    离散化思想
    POJ 2777 Count Color (线段树)
    POJ 1823 Hotel (线段树)
  • 原文地址:https://www.cnblogs.com/wangzaizhen/p/5196225.html
Copyright © 2011-2022 走看看