226. Invert Binary Tree
来源:互联网 发布:mac文件导入移动硬盘 编辑:程序博客网 时间:2024/05/16 02:14
题目:翻转二叉树
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9to
4 / \ 7 2 / \ / \9 6 3 1
题意:
如上如所示,将给定的二叉树按照根节点中间对称线进行翻转,左子树与右子树值相互对调。
转载地址:http://www.cnblogs.com/grandyang/p/4572877.html
思路一:
递归实现,利用一个临时TreeNode*变量辅助完成左右子节点的交换,直接在交换过程中进行递归即可完成。
代码:C++版:0ms
/** * 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) { if (!root) return NULL; TreeNode *tmp = root->left; //实现一个交换即可 root->left = invertTree(root->right); root->right = invertTree(tmp); return root; }};
思路二:
迭代完成,使用queue队列辅助完成二叉树的迭代遍历,并完成左右子节点的交换。先把根节点排入队列中,然后从队中取出来,交换其左右节点,如果存在则分别将左右节点在排入队列中,以此类推直到队列中没有节点了停止循环,返回root即可。
代码:C++版:0ms
/** * 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) { if (!root) return NULL; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode *node = q.front(); q.pop(); TreeNode *tmp = node->left; //左右交换 node->left = node->right; node->right = tmp; if (node->left) q.push(node->left); //左右子节点分别入队列 if (node->right) q.push(node->right); } return root; }};
0 0
- 226.Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- Jquery EasyUI增删改查实现步骤
- Spring4笔记----Bean 的生命周期方法
- WebSocket
- React-Native 基础(三) 使用State改变状态
- ffmpeg AVFilter
- 226. Invert Binary Tree
- 图片相关
- get! 13张IT职业技能&学习图谱
- 命令行执行 mvn package 和常见mvn命令
- EMail诞生记
- NanoPC-T2 Uboot启动过程分析 - 2-4 init_sequence_f[] part 2
- 记录自己的成长
- java数据结构之排序_排序算法的时空复杂度介绍
- Java中接口和抽象类