您的位置:首页 > 其它

Binary Tree Postorder Traversal

2014-04-09 16:49 162 查看
/*
* Solution.cpp
*
*  Created on: 2014年4月9日
*      Author: William
*/

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

// Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};

class Solution {
public:
void postorderTraversalRecursive(TreeNode *root, vector<int> *ans) {
if (root != NULL) {
postorderTraversalRecursive(root->left, ans);
postorderTraversalRecursive(root->right, ans);
ans->push_back(root->val);
}
}

vector<int> postorderTraversal(TreeNode *root) {
// Recursive
/*vector<int> ans;
postorderTraversalRecursive(root, &ans);
return ans;*/

// Iterative
vector<int> ans;
if (root == NULL) return ans;
stack<TreeNode*> stk;
stk.push(root);
TreeNode *cur;
while (!stk.empty()) {
cur = stk.top();
if (cur->left == NULL && cur->right == NULL) {
stk.pop();
ans.push_back(cur->val);
} else {	// This part is very clever:
// If the current node has left/right child, we push the children nodes into the stack
// in right-left order(which makes the pop order becomes left-right).
// Then we make the current node has no child, so it can be treated as a leaf.
// Basically, this way we put all the nodes into the stack in post-order(reverse).
// This way, we avoid using flag to indicate visited node.
if (cur->right != NULL) {
stk.push(cur->right);
cur->right = NULL;
}
if (cur->left != NULL) {
stk.push(cur->left);
cur->left = NULL;
}
}
}
return ans;
}
};

//int main() {
//	return 0;
//}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: