Invert Binary Tree -- leetcode
来源:互联网 发布:mac脚本编辑器 用途 编辑:程序博客网 时间:2024/05/29 07:31
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9to
4 / \ 7 2 / \ / \9 6 3 1
算法一,dfs递归
基本思路,就是将每一个节点的左右孩子指针互换。
/** * 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 root; const auto left = root->left; root->left = invertTree(root->right); root->right = invertTree(left); return root; }};
其实,此题中序,后序,前序遍历都可以。即交换左右孩子结点指针,这个操作,顺序比较灵活。
可以在子树完成之前做,也可以完成之后做。彼此之间没有依赖关系。
class Solution {public: TreeNode* invertTree(TreeNode* root) { if (!root) return root; swap(root->left, root->right); invertTree(root->left); invertTree(root->right); return root; }};
算法二,广度优先,非递归
基本思路,同上, 将每一个节点的,左右孩子互换。
class Solution {public: TreeNode* invertTree(TreeNode* root) { if (!root) return root; queue<TreeNode*> q; q.push(root); while (!q.empty()) { auto node = q.front(); q.pop(); swap(node->left, node->right); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } return root; }};
0 0
- [leetcode] Invert Binary Tree
- [LeetCode]Invert Binary Tree
- leetcode:Invert Binary Tree
- LeetCode Invert Binary Tree
- LeetCode | Invert Binary Tree
- leetcode--Invert Binary Tree
- [leetcode] Invert Binary Tree
- [LeetCode] Invert Binary Tree
- LeetCode Invert Binary Tree
- leetcode : Invert Binary Tree
- [LeetCode] Invert Binary Tree
- [Leetcode]Invert Binary Tree
- LeetCode: Invert Binary Tree
- LeetCode Invert Binary Tree
- leetcode: Invert Binary Tree
- LeetCode Invert Binary Tree
- LeetCode || Invert Binary Tree
- LeetCode:Invert Binary Tree
- C语言strstr()函数常用示例详解[求一个字符串在另一个字符串中出现的次数]
- Android:30分钟弄明白Touch事件分发机制
- 正则表达式
- 查看某个文件的git 历史和更改
- Python类的专用方法
- Invert Binary Tree -- leetcode
- 华为测试 字符加密
- 使用Parse.com作为后端服务,开发iOS APP
- 分享一个Linux下安装ASM+ORACLE的自动化脚本(三)
- 破解android手机付费软件视频教程
- Python之sys模块小探
- 单向链表简单实现
- 【SSH系列】——手动搭建SSH环境
- 提高系统性能数据库设计的横向分割和纵向分割技术 .