leetcode 226. Invert Binary Tree
2016-05-24 14:35
363 查看
Invert a binary tree.
to
好久没有做过题啦,写bfs和dfs都感觉犹豫:-(
[/code]
4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1 二叉树的递归实现: [code]<span style="font-size:18px;">/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* invertTree(struct TreeNode* root) { if(root==NULL) return root; invertTree(root->left); invertTree(root->right); struct TreeNode* T; T=root->left; root->left=root->right; root->right=T; return root; }</span> <span style="font-size:18px;">然后是非递归形式的,使用队列实现,: </span><pre name="code" class="cpp"><span style="font-size:18px;">/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { queue<TreeNode*> q; if(root) q.push(root); struct TreeNode *c,*tmp; while(!q.empty()) { c=q.front(); q.pop(); tmp=c->left; c->left=c->right; c->right=tmp; if(c->left) q.push(c->left); if(c->right) q.push(c->right); } return root; } };</span>
好久没有做过题啦,写bfs和dfs都感觉犹豫:-(
[/code]
相关文章推荐
- MyBatis学习总结——实现关联表查询
- meidaPlayer java.io.IOException: setDataSource failed.: status=0x800000
- 图片铺满整个浏览器,兼容ie8的写法
- CSS3 Border-image
- Sublime Text3 配置Node.js运行命令
- 多线程下载
- suzhoutexiao
- 按钮定时开关
- 递归和动态规划的算法题(1)
- iOS UDP广播
- 第10 11周 项目三 警察与厨师 (2)
- 关于数据库中字段空值的SQL排序的问题
- 仿今日头条和qq侧滑和智慧北京的小项目 1
- hdu 3944 DP? (预处理+卢卡斯定理)
- 如何从github上面拷贝源码
- 学习练习 java 程序设计园的周长面积
- 接口3
- mybatis学习(三)SqlSessionFactory
- Incorrect key file for table错误解决方法
- 第十三周-阅读程序