Binary Tree Postorder Traversal
来源:互联网 发布:佛教 知乎 编辑:程序博客网 时间:2024/05/29 17:05
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?
Solution:
/** * 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> res; if(root == NULL) return res; stack<TreeNode*> st; st.push(root); TreeNode* flag = root; while(!st.empty()) { TreeNode* top = st.top(); if((top->left == NULL && top->right == NULL) || (flag != NULL && (flag == top->left || flag == top->right))) { res.push_back(top->val); st.pop(); flag = top; } else { if(top->right != NULL) st.push(top->right); if(top->left != NULL) st.push(top->left); } } return res; }};
0 0
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- cpp整理笔记:标准I/O的工作原理
- Leetcode Q15: 3Sum
- Windows 10 下支付宝无法安装数字证书解决方法
- E. Frogger
- 面试题38_数字在排序数组中出现的次数
- Binary Tree Postorder Traversal
- Linux 进程通信之管道
- C语言宏中"#"和"##"的用法
- 【unity优化六】代码
- 【CodeForces】Gargari and Bishops
- 异常处理:借书
- 营业额统计 splayTree
- HDU - 4280 Island Transport(ISAP)
- 选择排序