[LeetCode]Binary Tree Postorder Traversal

2014-11-24 02:34:42 · 作者: · 浏览: 1
/** 
 * 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 postorderTraversal(TreeNode *root) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        vector result;  
        TreeNode* curNode = root;  
        stack 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; } };