LeetCode | 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?

思路:

常规的后序遍历。

代码:

递归版本

/**
 * 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> v;
    vector<int> postorderTraversal(TreeNode *root) {
        postorder(root);
        return v;
    }
    
    void postorder(TreeNode* root)
    {
        if(root==NULL)
            return;
        else
        {
            postorder(root->left);
            postorder(root->right);
            v.push_back(root->val);
        }
    }
};

非递归版本

/**
 * 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*> node;
        stack<int> nodeStatus;
        
        if(root != NULL){
            node.push(root);
            nodeStatus.push(0);
        }
        
        while(!node.empty()){
            TreeNode* n = node.top();
            node.pop();
            int status = nodeStatus.top();
            nodeStatus.pop();
            
            if(status == 0){
                node.push(n);
                nodeStatus.push(1);
                if(n->right != NULL){
                    node.push(n->right);
                    nodeStatus.push(0);
                }
                if(n->left != NULL){
                    node.push(n->left);
                    nodeStatus.push(0);
                }
            }
            else{
                result.push_back(n->val);
            }
        }
        
        return result;
    }
};

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17308867
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞