[Leetcode] 145. Binary Tree Postorder Traversal 解题报告
来源:互联网 发布:java gbk乱码 编辑:程序博客网 时间:2024/06/05 17:29
题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
思路:
刚开始的时候百思不得其解,后来发现其实完全可以参照Leetcode 144的解法。我们只要稍微修改先序遍历(输出根节点后,先遍历右子树,然后遍历左子树),那么得到的结果刚好是后续遍历的逆序。因此思路就很简单了:只需要在Leetcode 144的代码的基础上,加上reverse(ret.begin(), ret.end())即可。时间复杂度和空间复杂度完全同Leetcode 144。
代码:
/** * 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: vector<int> postorderTraversal(TreeNode* root) { vector<int> ret; if(root == NULL) { return ret; } stack<TreeNode*> s; s.push(root); while(!s.empty()) { TreeNode* node = s.top(); s.pop(); if(node->left) { s.push(node->left); } if(node->right) { s.push(node->right); } ret.push_back(node->val); } reverse(ret.begin(), ret.end()); return ret; }};
0 0
- [LeetCode]Binary Tree Postorder Traversal,解题报告
- LeetCode 解题报告 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解题报告
- 【LeetCode】145.Binary Tree Postorder Traversal(Hard)解题报告
- LeetCode—Binary Tree Postorder Traversal 解题报告
- leetCode解题报告之Binary Tree Postorder Traversal
- [LeetCode OJ] Binary Tree Postorder Traversal 解题报告
- LeetCode(145) Binary Tree Postorder Traversal解题报告
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal解题报告
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode 解题报告 Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal 解题报告
- [LeetCode]145.Binary Tree Postorder Traversal
- java之final关键字、包、封装
- 说一说本人对linux系统学习的方法和经验
- 新路程------uart驱动和tty(2)
- 移植QT-MYSQL到ARM(客户端版和完整版)
- Activity转场动画
- [Leetcode] 145. Binary Tree Postorder Traversal 解题报告
- 再议字符集和编码
- CodeForces
- Map 的遍历方法
- 微信小程序客服接口
- ARP协议 你不能不知道的
- 喵哈哈村的魔力源泉(4)-(单调队列优化)
- 简单实现上拉下拉,增加头条目和尾条目的RecyclerView
- [UE4]注意事项,插件中蓝图方法库在C++中的使用