LeetCode Binary Tree Postorder Traversal
来源:互联网 发布:电子数据库 编辑:程序博客网 时间:2024/06/03 20:12
1.题目
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?
2.解决方案1
class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; if(root == NULL){ return res; } stack<TreeNode*> stackNode; stackNode.push(root); TreeNode* preNode = NULL; while(stackNode.empty() == false){ TreeNode* curNode = stackNode.top(); bool isLeafNode = curNode->left == NULL && curNode->right == NULL; if(isLeafNode || (preNode != NULL && (preNode == curNode->left || preNode == curNode->right))){ res.push_back(curNode->val); stackNode.pop(); preNode = curNode; }else{ if(curNode->right != NULL){ stackNode.push(curNode->right); } if(curNode->left != NULL){ stackNode.push(curNode->left); } } } return res; }};
思路:非递归的方式要用stack来辅助。
关键点1:
我们知道stack是先进的后出,而后序遍历是要先访问左节点,所以我们要先把右节点push到stack中,再push左节点。
关键点2:
叶子可以直接输出了,但如果一个节点有左右一个节点,也是要输出的,输出的时机是这题的难点。这里又增加了一个变量,来记录之前输出的点,假如一个节点的左右叶子节点有一个输出了,然后再访问到这个节点,因为stack的特性,说明左右节点都已经输出了,说明这个时候就可以输出这个根节点了。
3.解决方案2
class Solution {public: vector<int> result; void HXBL(TreeNode* root){ if(root == nullptr)return; if(root->left != NULL){ HXBL(root->left); } if(root->right != NULL){ HXBL(root->right); } if(root != NULL){ result.push_back(root->val); } } vector<int> postorderTraversal(TreeNode *root) { result.clear(); HXBL(root); return result; }};
递归当然简单了,就是慢。慢就是bug。
http://www.waitingfy.com/archives/1608
0 0
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- leetcode Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- LeetCode | Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- 读《汇编语言》II
- android屏幕截图,android怎么截取整个屏幕
- mac使用ssh
- 游戏开发者也会在 Apple Watch 上演示最新成果
- 反编译C程序为汇编代码,汇编代码执行过程的分析与思考
- LeetCode Binary Tree Postorder Traversal
- 黑马程序员_Java_多线程
- ZOJ - 3809 The Himalayas 暴力
- JQuery获取子孩子和兄弟元素的方法
- 日经社説 20150308 何が患者連続死を招いたか
- 编译时出现fatal error C1853: "debug/xxx.pch" is not a precomplied header file with......错误的原因及解决办法(转)
- 社説 20150308 福島の避難住民 「帰還」見据えた支援の強化を
- .net学习第五天
- C++11中的final关键词