[LeetCode] Binary Tree Postorder Traversal

Binary Tree Postorder Traversal

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?

解题思路:

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<int> postorderTraversal(TreeNode *root) {
        vector<int> result;
        postOrder(root, result);
        return result;
    }
    
    void postOrder(TreeNode *node, vector<int>& result){
        if(node==NULL){
            return;
        }
        postOrder(node->left, result);
        postOrder(node->right, result);
        result.push_back(node->val);
    }
};


2、但是题目要求不能用递归。此前学长跟我说,若递归改成非递归,无非就是用栈或者队列存储中间结果。这里我们用栈来存储中间结果。注意到,先遍历的后进栈,因此,最先进栈的是父节点,然后是右孩子,最后是左孩子。这里我们需要两个栈,一个存储左孩子栈,一个存储最终结果栈。代码如下:

/**
 * 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> result;
        
        stack<TreeNode*> s;         //最终结果栈
        stack<TreeNode*> sLeftNode; //左孩子栈
        TreeNode* node=root;
        
        while(node!=NULL||!sLeftNode.empty()){
            if(node!=NULL){
                s.push(node);
                if(node->left!=NULL){
                    sLeftNode.push(node->left);
                }
                node=node->right;
            }else{
                node=sLeftNode.top();
                sLeftNode.pop();
            }
        }
        while(!s.empty()){
            node=s.top();
            result.push_back(node->val);
            s.pop();
        }
        
        return result;
    }
};



你可能感兴趣的:(LeetCode,C++,栈)