思路:递归解法是trivial的,很简单,过一过就行了,code如下:
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { if(root){ vector<int> left, right,ret; left = postorderTraversal(root ->left); int len = left.size(); for(int i=0;i<len;i++) ret.push_back(left[i]); right = postorderTraversal(root ->right); len = right.size(); for(int i=0;i<len;i++) ret.push_back(right[i]); ret.push_back(root->val); return ret; } vector<int> temp; return temp; } };
用迭代法的规则(T_T!,写了好久,主要是节点遍历计数没有把握好,搞得好狼狈),反正前序、中序、后序遍历都是一个过程,主要是记数过程,count=0, 1, 2的时候分别是前序、中序、后序插入元素的时候。
class Solution { public: vector<int> postorderTraversal(TreeNode *root){ stack<TreeNode *> p; vector<int> ret; map<TreeNode *,int> state; TreeNode *t; if(root){ p.push(root); while(!p.empty()){ t = p.top(); if(state[t] == 0){ state[t]++; while(t->left){ t = t->left; p.push(t); state[t]++; } } else if(state[t] == 1){ state[t]++; if(t->right){ t = t->right; p.push(t); } } else{ ret.push_back(t->val); p.pop(); } } } return ret; } };