145. Binary Tree Postorder Traversal
来源:互联网 发布:数据录入员笔试试题 编辑:程序博客网 时间:2024/05/21 10:46
方法一:
先找最左孩子,只有最左孩子同时是叶子节点,才是目标节点,否则迭代最左孩子的右孩子。
class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int> vt; stack<TreeNode*> st; if(root==NULL) return vt; while(root!=NULL||!st.empty()) { while(root) { if(!st.empty()&&st.top()==root) break; st.push(root); root=root->left; st.top()->left=NULL; } if(!st.empty()) { root=st.top(); if(root->right) { root=root->right; st.top()->right=NULL; } else { vt.push_back(root->val); st.pop(); if(!st.empty()) root=st.top(); else root=NULL; } } } return vt; }};
方法2:后序遍历的顺序是left -right-root;现在的出栈顺序是root ,right,left。将结果翻转即可
class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int> vt; stack<TreeNode*> st; if(!root) return vt; st.push(root); while(!st.empty()) { root=st.top(); st.pop(); vt.push_back(root->val); if(root->left)st.push(root->left); if(root->right)st.push(root->right); } reverse(vt.begin(), vt.end()); return vt; }};
0 0
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 16.8.14 C组总结
- leetcode_c++:Text Justification(068)
- 26. Remove Duplicates from Sorted Array
- 反射
- JZOJ8.14(C组)帕秋莉·诺雷姬
- 145. Binary Tree Postorder Traversal
- 错误记录三
- 获取系统日期和24小时制时间
- 批处理之命令
- POJ-2463 Bungee Jumping (简单物理题)
- jquery知识
- java的面向对象编程一
- 防止Class类反编译的方法,对Class进行加密
- POJ 3278 Catch That Cow(简单BFS)