Binary Tree Postorder Traversal

来源:互联网 发布:md5加密 java代码 编辑:程序博客网 时间:2024/06/08 02:03

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

// RECURSIVE VERSION:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void postorderTraversalHelper(vector<int> & solution, TreeNode * node){
        if (node!=NULL){
            postorderTraversalHelper(solution, node->left);
            postorderTraversalHelper(solution, node->right);
            solution.push_back(node->val);
        }
    }
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> solution;
        postorderTraversalHelper(solution, root);
        return solution;
    }
};

// ITERATIVE VERSION:

/**
 * 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) {
        vector<int> solution;
        if (!root) return solution;
        
        stack<TreeNode *> mystack;
        stack<TreeNode *> output;
        
        mystack.push(root);
        while (!mystack.empty()){
            TreeNode * curr = mystack.top();
            output.push(curr);
            mystack.pop();
            if (curr->left)
                mystack.push(curr->left);
            if (curr->right)
                mystack.push(curr->right);
        }
        
        while (!output.empty()){
            solution.push_back(output.top()->val);
            output.pop();
        }
        
        return solution;
    }
};

0 0
原创粉丝点击