算法题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 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值