LeetCode 145. Binary Tree Postorder Traversal
来源:互联网 发布:知乎美女看这 编辑:程序博客网 时间:2024/04/28 19:41
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]
.
Stack Problem, One example will make this question easy to tackle.
In this example, the post-order sequence is: 4, 5, 2, 6, 3, 1.
The process will be.... We first push 1 onto stack, Get the top element, pop it off, then push the left and right child.....
vector<int> postorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> res; stack<TreeNode*> nodes; nodes.push(root); while(!nodes.empty()) { TreeNode* tmp = nodes.top(); nodes.pop(); res.push_back(tmp->val); if(tmp->left) nodes.push(tmp->left); if(tmp->right) nodes.push(tmp->right); } reverse(res.begin(), res.end()); return res; }
Another way of asking this question is to implement a post-order iterator which has getNext() method, and hasNext() method.
1 / \ 4 2 / \ 3 6 The post order is: 4 3 6 2 1 (left substree, root, right substree)
class postOrderIterator { stack<TreeNode*> nodes;public: void findNextLeave(TreeNode* root) { TreeNode* curr = root; while(curr) { nodes.push_back(curr); if(curr->left) curr = curr->left; else if(curr->right) curr = curr->right; } } bool hasNext() { return !nodes.empty(); } int getNext() { TreeNode* res = nodes.top(); nodes.pop(); while(!nodes.empty()) { TreeNode* tmp = nodes.top(); if(res == tmp->left) { // left is done, traversal the right. findNextLeave(tmp->right); } } return res->val; }}
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
- 博客已搬至自己搭建的博客处
- 文件处理
- Android学习(18) -- 数据存储之openFileOutput
- AT4 more about the sphere
- 基于java的网络抓包方法
- LeetCode 145. Binary Tree Postorder Traversal
- Android学习(20) -- 数据存储之SharedPreferences(存储账号密码)
- LeetCode 272. Closest Binary Search Tree Value II(二叉搜索树查找)
- LeetCode 226. Invert Binary Tree
- LoG, DoG, Pyramid 与SIFT 算法【未写完, 暂停更新】
- LeetCode 102. Binary Tree Level Order Traversal
- BFS入门题目 POJ1426 1753 3414 3669
- TransE论文第2节:翻译模型
- Openlayers2卷帘功能的实现