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]
.
递归很简单,迭代呢?
方法1: 内存占用太多,过不了。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stack>
#include <vector>
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> post_tree;
if (root == NULL) {
return post_tree;
}
stack<pair<TreeNode*, bool>> stack_tree;
stack_tree.push(make_pair(root, false));
while (!stack_tree.empty()) {
auto iter = stack_tree.top();
if (iter.second || iter.first->left == NULL && iter.first->right == NULL) {
post_tree.push_back(iter.first->val);
stack_tree.pop();
}
else {
if (iter.first->right != NULL) {
stack_tree.push(make_pair(iter.first->right, false));
}
if (iter.first->left != NULL) {
stack_tree.push(make_pair(iter.first->left, false));
}
iter.second = true;
}
}
return post_tree;
}
};
方法2:写的很乱,总算过了。
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> post_tree;
if (root == NULL) {
return post_tree;
}
TreeNode *node = NULL;
TreeNode *last_visited = NULL;
stack<TreeNode*> stack_tree;
stack_tree.push(root);
while (!stack_tree.empty()) {
node = stack_tree.top();
if (node->left == NULL && node->right == NULL ||
node->right != NULL && node->right == last_visited ||
node->right == NULL && node->left == last_visited) {
post_tree.push_back(node->val);
last_visited = node;
stack_tree.pop();
}
else {
do {
while (node->left != NULL && node->left != last_visited) {
node = node->left;
stack_tree.push(node);
}
if (node->right != NULL) {
node = node->right;
stack_tree.push(node);
}
} while (node->left != NULL || node->right != NULL);
}
}
return post_tree;
}
};
有待优化。
/** * Definition for binary tree * 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> result; stack<TreeNode*> nodes; TreeNode *prev = NULL; while (root != NULL || !nodes.empty()) { while (root != NULL) { nodes.push(root); root = root->left; } if (!nodes.empty()) { root = nodes.top(); if (root->right == NULL || root->right == prev) { result.push_back(root->val); nodes.pop(); prev = root; root = NULL; } else { root = root->right; } } } return result; } };