非递归的话,用一个栈node_stack维护深搜。
每访问一个结点,
1) 若该结点未被访问过,则将它标记为已访问。考察它是否是叶子
若是,将val值压入vector<int>中,弹出该结点;
若不是,先将它的右儿子(非空的话)压入node_stack中,再将它的左儿子(非空的话)压入node_stack中。注意到因为每次都是访问栈顶,所以要先压右儿子后压左儿子,来保证后序遍历。
2) 若该结点已被访问,则将val值压入vector<int>中,弹出该结点
非递归代码:
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> ret; stack<pair<TreeNode*, bool>> node_stack; if (root == NULL) { return ret; } node_stack.push(make_pair(root, false)); while (node_stack.empty() == false ) { auto top = node_stack.top(); if (top.second == true) { ret.push_back(top.first->val); node_stack.pop(); continue; } else { node_stack.top().second = true; // cannot use top.second=true here! } bool child = true; if (top.first->right != NULL) // right first { node_stack.push(make_pair(top.first->right, false)); child = false; } if (top.first->left != NULL) { node_stack.push(make_pair(top.first->left, false)); child = false; } if (child == true) { ret.push_back(top.first->val); node_stack.pop(); } } return ret; } };
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> ret; postorderTraversal_inner(root, ret); return ret; } private: void postorderTraversal_inner(TreeNode* root, vector<int>& vt_out) { if (root == NULL) { return ; } postorderTraversal_inner(root->left, vt_out); postorderTraversal_inner(root->right, vt_out); vt_out.push_back(root->val); } };