/**
* Definition for binary tree
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> result;
TreeNode* curNode = root;
stack<TreeNode*> nodeStack;
while(curNode || !nodeStack.empty())
{
//...delay the visit to the returned function
if(!curNode)
{
while(!nodeStack.empty() && nodeStack.top()->right == curNode)
{
curNode = nodeStack.top();
nodeStack.pop();
result.push_back(curNode->val);
}
if(!nodeStack.empty()) curNode = nodeStack.top()->right;
else curNode = NULL;
}
//...process the left subtree call
while(curNode)
{
nodeStack.push(curNode);
curNode = curNode->left;
}
//...process the right subtree call
if(!nodeStack.empty())
{
curNode = nodeStack.top();
curNode = curNode->right;
}
}
return result;
}
};
[LeetCode]Binary Tree Postorder Traversal
最新推荐文章于 2022-07-19 11:52:33 发布