翻转二叉树
2015-07-22 10:52
197 查看
1.二叉树初始化,插入数值,填满二叉树
2.按层打印原始二叉树
3.翻转二叉树
4.按层打印翻转后的二叉树
代码如下:
2.按层打印原始二叉树
3.翻转二叉树
4.按层打印翻转后的二叉树
代码如下:
#include <iostream> #include <string> #include <vector> using namespace std; struct TreeNode{ int val; TreeNode *left; TreeNode *right; }; class Solution{ public: TreeNode *invertTree(TreeNode *root) { if (root == NULL) return NULL; TreeNode *tmp; tmp = root->left; root->left = root->right; root->right = tmp; invertTree(root->left); invertTree(root->right); return root; } }; TreeNode *Insert(int x, TreeNode *root) { if (root == NULL) { root = (TreeNode *)malloc(sizeof(struct TreeNode)); if (root == NULL) { return NULL; } else { root->val = x; root->left = NULL; root->right = NULL; } } else { if (x < root->val) { root->left=Insert(x,root->left); } else if (x > root->val) { root->right=Insert(x,root->right); } } return root; } TreeNode *print(TreeNode *root) { if (root == NULL) return NULL; vector<TreeNode *> vec; vec.push_back(root); int cur = 0; int last = 1; while (cur < vec.size()) { last = vec.size(); while (cur < last) { cout << vec[cur]->val << " "; if (vec[cur]->left != NULL) vec.push_back(vec[cur]->left); if (vec[cur]->right != NULL) vec.push_back(vec[cur]->right); ++cur; } } } int main(int argc, char *argv[]) { vector<int> num = {4,2,7,1,3,6,9}; TreeNode* T = NULL; for (auto s1 = num.begin(); s1 != num.end(); ++s1) { T=Insert(*s1,T); } print(T); Solution Test; Test.invertTree(T); cout << endl; print(T); return 0; }
相关文章推荐
- 【技术分享】CSS 实现渐变色背景
- Add Binary
- UML中的六大关系
- stm32的MDA应用设置
- git 连接不同的服务器地址
- Windows&Linux 命令行运行jar里的JUnit
- 理解 Ruby Symbol (Ruby中的符号)
- 1048. Find Coins
- 基于adt bundle的Android环境搭建
- 缓存的一些理解
- hdoj.2577 How to Type【模拟】 2015/07/22
- 计算机网络之网络协议
- ThinkPHP验证码类
- 桶排序
- sql 2008 权限角色控制
- ubuntu14环境下,通过apt-get 下载oracle-java8
- Android基础总结——Activity生命周期与横竖屏切换
- asp.net c# 断点续传 下载 Accept-Ranges
- redis加mybatis,org.apache.commons.pool2.impl.GenericObjectPoolConfig记住这个是pool2!!
- hadoop1.x和2.x版本配置的区别