226. Invert Binary Tree(unsolved)
来源:互联网 发布:淘宝一元拍卖 编辑:程序博客网 时间:2024/06/06 03:23
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
方法一:递归
思路:深度优先搜索,用递归的方式,交换完root的左右后,交换root左右子树的左右子树。
/** * 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==NULL) return NULL; TreeNode*temp=root->left; root->left=root->right; root->right=temp; invertTree(root->left); invertTree(root->right); return root; }};
方法二:迭代
思想:使用广度优先搜索,设立一个队列,每次都把一个节点压进去,然后调换其左右节点,把其左右节点压进去后,再把这个节点弹出来
/** * 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==NULL) return NULL; queue<TreeNode*> p; p.push(root); while(!p.empty()) { swap(p.front()->left,p.front()->right); if(p.front()->right) p.push(p.front()->right); if(p.front()->left) p.push(p.front()->left); p.pop(); } return root; }};
0 0
- 226. Invert Binary Tree(unsolved)
- 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
- 1. 为加法计算器程序添加一个模态对话框
- Add unit test for unmanaged code
- Dual Palindromes<uscao>1.2 <进制转换+枚举>
- Linux命令之route - 显示和操作IP路由表
- 快速排序
- 226. Invert Binary Tree(unsolved)
- Android Notification 详解--设置闹铃、振动、灯光
- MYSQL——DQL : 数据查询语句(select)
- CEF3控件的安装
- 【android开发】类抽屉菜单(自定义ViewGroup)的实现
- SQLite、MySQL和PostgreSQL 三种关系数据库哪个好?
- 数值微分法(DDA)生成直线
- 【图文】用Origin作多组红外数据对比图
- Java IO最详解