剑指Offer算法实现之十九:二叉树的镜像
来源:互联网 发布:批发建筑材料的软件 编辑:程序博客网 时间:2024/05/22 14:56
题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。
二叉树节点定义如下:
struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight;};思路:
遍历二叉树,交换每个节点的左右子树
编译环境:ArchLinux+Clang3.3, C++11
实现一:
#include <iostream>#include <cstring>using namespace std;struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight;};/** 做镜像 **/void do_mirror(BinaryTreeNode *pRoot){ if (!pRoot) return; do_mirror(pRoot->m_pLeft); do_mirror(pRoot->m_pRight); swap(pRoot->m_pLeft, pRoot->m_pRight);}/** * 根据二叉树的“单”字符表示形式(形如"1(2,3(,4))")创建二叉树。 * 区间:[start, end)**/BinaryTreeNode *createTree(const char *start, const char *end){ if (start >= end) { return nullptr; } if (end - start == 1) { return new BinaryTreeNode{*start-'0', nullptr, nullptr}; } const char *start1 = start+2; const char *end1 = start+2; int cnt = 0; while (true) { if (*end1 == '(') cnt++; if (*end1 == ')') cnt--; if (*end1 == ',' && cnt == 0) break; end1++; } const char *start2 = end1+1; const char *end2 = end1+1; cnt = 0; while (true) { if (*end2 == '(') cnt++; if (*end2 == ')' && cnt == 0) break; if (*end2 == ')') cnt--; end2++; } return new BinaryTreeNode{*start-'0', createTree(start1, end1), createTree(start2, end2)};}/** 打印二叉树 **/void printTree(BinaryTreeNode *pRoot){ if (!pRoot) return; cout << pRoot->m_nValue; if (pRoot->m_pLeft || pRoot->m_pRight) cout << '('; if (pRoot->m_pLeft) { printTree(pRoot->m_pLeft); } if (pRoot->m_pLeft && pRoot->m_pRight) cout << ','; if (pRoot->m_pRight) { printTree(pRoot->m_pRight); } if (pRoot->m_pLeft || pRoot->m_pRight) cout << ')';}/** Wrapper **/BinaryTreeNode *createTree(const char *str){ return createTree(str, str+strlen(str));}int main(){ BinaryTreeNode *pRoot = createTree("8(6(5,7),2(9,3))"); printTree(pRoot); cout << endl; do_mirror(pRoot); printTree(pRoot); cout << endl;}
- 剑指Offer算法实现之十九:二叉树的镜像
- 二叉树的镜像[剑指offer]之python实现
- java实现二叉树的镜像--剑指offer
- 剑指offer:二叉树的镜像 代码实现
- 剑指offer---二叉树的镜像---java实现
- 剑指offer系列之十七:二叉树的镜像
- 【剑指offer】之二叉树的镜像
- 码农小汪-剑指Offer之16-二叉树的镜像
- 剑指offer系列之17:二叉树的镜像
- 剑指offer(三十四)之二叉树的镜像
- 剑指offer 之 二叉树的镜像
- 剑指offer之二叉树的镜像(Python)
- 【剑指offer】二叉树的镜像
- [剑指Offer]二叉树的镜像
- 剑指offer--二叉树的镜像
- 剑指Offer-二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指 offer:二叉树的镜像
- C语言函数指针基础
- 内核态基本套接字编程
- UVa10250 – The Other Two Trees
- Qt学习之对话框与主窗口的创建
- cocos2d-x手机游戏开发笔记(二)--坐标系
- 剑指Offer算法实现之十九:二叉树的镜像
- Threads in Spring
- 基于Tomcat7、Java、WebSocket的服务器推送聊天室
- Windows平台基于多进程的echo服务器简单实现
- 每日一题(62) - 和为s的连续正整数序列
- Elastisearch相关
- KeyCode键码值表
- .NET框架设计—常被忽视的框架设计技巧
- 开源中国iOS客户端学习——(一)Prefix.pch文件