LeetCode145:Binary Tree Postorder Traversal

mickole發表於2014-02-17

題目:

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].

Note: Recursive solution is trivial, could you do it iteratively?

解題思路:

後序遍歷的非遞迴實現與前序遍歷和中序遍歷的非遞迴不同,對於根節點,必須當其右孩子都訪問完畢後才能訪問,所以當根節點出棧時,要根據標誌位判斷是否為第一次出棧,如果是,則將其標誌位置為FALSE,然後再次入棧,先訪問其右孩子,當某個節點出棧時且其標誌位為false,說明該節點為第二次出棧,即表示其右孩子都已處理完畢,可以訪問當前節點了

實現程式碼:

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

/**
Given a binary tree, return the postorder traversal of its nodes' values.
*/
 

struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;    
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void addNode(TreeNode* &root, int val)
{
    if(root == NULL)
    {
        TreeNode *node = new TreeNode(val);
        root = node;
    }
    else if(root->val < val)
    {
        addNode(root->right, val);
    }
    else if(root->val > val)
    {
        addNode(root->left, val);
    }
}

void printTree(TreeNode *root)
{
    if(root)
    {
        cout<<root->val<<" ";
        printTree(root->left);
        printTree(root->right);
    }
}
struct Node
{
    TreeNode *treeNode;
    bool isFirst;
};

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> ivec;
        if(root)
        {                
            stack<Node*> istack;
            TreeNode *p = root;
            while(!istack.empty() || p)
            {
                while(p)
                {
                    Node *tmpNode = new Node();
                    tmpNode->treeNode = p;
                    tmpNode->isFirst = true;
                    istack.push(tmpNode);
                    p = p->left;
                }
                if(!istack.empty())
                {
                    Node *node = istack.top();
                    istack.pop();
                    if(node->isFirst)//第一次出棧, 
                    {
                        node->isFirst = false;
                        istack.push(node);
                        p = node->treeNode->right;
                    }
                    else//表示其右孩子都已經訪問了,可以訪問當前節點了 
                    {
                        ivec.push_back(node->treeNode->val);
                    }
                }
                
            }
            
        }
        return ivec;
                       
    }
};
int main(void)
{
    TreeNode *root = new TreeNode(5);
    addNode(root, 7);
    addNode(root, 3);
    addNode(root, 15);
    addNode(root, 1);
    printTree(root);
    cout<<endl;
    
    Solution solution;
    vector<int> v = solution.postorderTraversal(root);
    vector<int>::iterator iter;
    for(iter = v.begin(); iter != v.end(); ++iter)
        cout<<*iter<<" ";
    cout<<endl;
    
    return 0;
}

相關文章