http://oj.leetcode.com/problems/binary-tree-postorder-traversal/
树的后序遍历,可以使用递归,也可以使用栈,下面是栈的实现代码
#include <iostream> #include <vector> #include <stack> using namespace std; 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> ans; if(root == NULL) return ans; stack<TreeNode*> myStack; myStack.push(root); TreeNode* lastPop = NULL; TreeNode* nodeTop = NULL; while(!myStack.empty()) { nodeTop = myStack.top(); if(nodeTop->right && lastPop != nodeTop->right) myStack.push(nodeTop->right); else if(nodeTop->right && lastPop == nodeTop->right) { ans.push_back(nodeTop->val); lastPop = nodeTop; myStack.pop(); continue; } if(nodeTop->left && (nodeTop->right &&lastPop != nodeTop->right || nodeTop->right == NULL && lastPop != nodeTop->left)) myStack.push(nodeTop->left); else if(nodeTop->left && (nodeTop->right && lastPop == nodeTop->right || nodeTop->right == NULL && lastPop == nodeTop->left)) { ans.push_back(nodeTop->val); lastPop = nodeTop; myStack.pop(); continue; } if(nodeTop->left == NULL && nodeTop->right == NULL) { ans.push_back(nodeTop->val); lastPop = nodeTop; myStack.pop(); } } return ans; } }; int main() { TreeNode *root = new TreeNode(1); TreeNode *n2 = new TreeNode(2); //TreeNode *n3 = new TreeNode(2); TreeNode *n4 = new TreeNode(4); //TreeNode *n5 = new TreeNode(5);*/ TreeNode *n6 = new TreeNode(3); TreeNode *n7 = new TreeNode(4); root->left = n2; //root->right = n3; n2->left = n4; //n2->right = n5;*/ //n3->left = n6; //n6->right = n7; Solution myS; myS.postorderTraversal(root); return 0; }