题目要求:
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]
.
代码:
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { stack<TreeNode*> st; vector<int> ret; if(root == NULL) return ret; TreeNode* cur = NULL; TreeNode* pre = NULL; st.push(root); while(!st.empty()) { cur = st.top(); if((cur->left == NULL && cur->right == NULL) || (pre != NULL && (cur->left == pre || cur->right == pre)))//如果是叶子节点或者是左右子孩子已经被访问过了,才能访问当前节点 { ret.push_back(cur->val); st.pop(); pre = cur; } else { if(cur->right != NULL) st.push(cur->right); if(cur->left != NULL) st.push(cur->left); } } return ret; } };