解题思路:与Leetcode 144 类似,不过在碰到当前指针为NULL时,先判断栈顶元素是否为NULL,为空,则表示上一个结点的右子树也遍历过,不为NULL,则向令当前指针指向栈顶结点的右指针,并向栈中push一个空指针。
/**
* Definition for a binary tree node.
* 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;
stack<TreeNode*> sta;
while (root != NULL) {
sta.push(root);
root = root->left;
while (!sta.empty() && root == NULL) {
if (sta.top() == NULL) {
sta.pop();
ans.push_back(sta.top()->val);
sta.pop();
} else {
root = sta.top()->right;
sta.push(NULL);
}
}
}
return ans;
}
};