【LeetCode】145. Binary Tree Postorder Traversal
来源:互联网 发布:sql 删除表中所有数据 编辑:程序博客网 时间:2024/06/05 11:07
【LeetCode】145. Binary Tree Postorder Traversal
【题目描述】
Given a binary tree, return the postorder traversal of its nodes' values.
Note: Recursive solution is trivial, could you do it iteratively?
【输入输出】
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
【解题思路】
Morris traversal:时间复杂度:O(n)空间复杂度:O(1)
【代码】
class Solution {public:vector postorderTraversal(TreeNode* root) {if (!root) return vector();vector ans;while (true) {ans.insert(ans.begin(), root->val);if (!root->left && !root->right) break;TreeNode* p = root;if (p->right) {p = p->right;while (p->left) p = p->left;p->left = root->left;root->left = NULL;}root = (root->right) ? root->right : root->left;}return ans;}};
class Solution {public:vectorpostorderTraversal(TreeNode* root) {if (!root) return vector ();vector ans;while (true) {ans.insert(ans.begin(), root->val);if (!root->left && !root->right) break;TreeNode* p = root;if (p->right) {p = p->right;while (p->left) p = p->left;p->left = root->left;root->left = NULL;}root = (root->right) ? root->right : root->left;}return ans;}};
0 0
- [LeetCode]145.Binary Tree Postorder Traversal
- [leetcode] 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal LeetCode
- Leetcode 145. Binary Tree Postorder Traversal
- [LeetCode]145. Binary Tree Postorder Traversal
- Leetcode 145. Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode-145.Binary Tree Postorder Traversal
- [leetcode] 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal
- [LeetCode]problem 145. Binary Tree Postorder Traversal
- Leetcode 145. Binary Tree Postorder Traversal
- [LeetCode] 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode:145. Binary Tree Postorder Traversal
- java.util.ResourceBundle使用详解
- nyoj 挑战密室 模拟题
- 设计模式-静态工厂
- 正则表达式从零开始学习系列(二)
- mysql 安装
- 【LeetCode】145. Binary Tree Postorder Traversal
- (转)深入理解JavaScript系列(2):揭秘命名函数表达式
- 使用node.js搭建一个简单的本地服务器
- Android studio 中类似eclipse中alt / 的快捷键
- JQUERY插件学习之jqPlot
- LONG型时间获取年月日,时分秒
- gdb调试
- MySQL增量备份与恢复实例
- leetcode 468. Validate IP Address