【LeetCode】226. Invert Binary Tree
来源:互联网 发布:ae2017汉化补丁 mac 编辑:程序博客网 时间:2024/05/01 12:59
Question
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9
to
4 / \ 7 2 / \ / \9 6 3 1
Code
BFS:
/** * 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 root; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* cur = q.front(); q.pop(); TreeNode* tmp = cur->left; cur->left = cur->right; cur->right = tmp; if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); } return root; }};
There is a simple recursion solution:
TreeNode* invertTree(TreeNode* root) { if (root==NULL) return NULL; TreeNode* tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root;}
Note
Be careful for the NULL pointer!
When you use a pointer, please make sure that it is availble!
0 0
- LeetCode 226. Invert Binary Tree
- [leetcode] 226.Invert Binary Tree
- [leetcode] 226. Invert Binary Tree
- 【LeetCode】226. Invert Binary Tree
- leetCode 226. Invert Binary Tree
- LeetCode #226. Invert Binary Tree
- [LeetCode]226. Invert Binary Tree
- 226. Invert Binary Tree LeetCode
- LeetCode 226. Invert Binary Tree
- LeetCode 226. Invert Binary Tree
- leetcode:226. Invert Binary Tree
- LeetCode 226. Invert Binary Tree
- [LeetCode]226. Invert Binary Tree
- leetcode 226. Invert Binary Tree
- 【LeetCode】226. Invert Binary Tree
- #leetcode#226. Invert Binary Tree
- LeetCode *** 226. Invert Binary Tree
- leetcode: 226. Invert Binary Tree
- Unable to find the ncurses libraries的解决办法
- 选择排序
- 学习shell script
- C++模版总结(2/2)
- MIT算法导论-第9讲-二叉查找树
- 【LeetCode】226. Invert Binary Tree
- 接下来,人生的规划
- jq如何获取文本值、输入值、属性值
- leetcode 3. Longest Substring Without Repeating Characters
- jersey 基于tomcat web service 开发 restful service
- 写分页时如何用jq获取当前标签文本的值
- eclipse maven搭建
- php线程安全与非线程安全安装包选择
- OpenCV 3.10+Visual Studio 2013+Camera