145. Binary Tree Postorder Traversal

145. 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 a binary tree node.
 * 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) {
        stack<TreeNode*> sta;

        TreeNode* cur;
        TreeNode* pre=NULL;
        vector<int> vec;
        if (root==NULL)
        {
            return vec;
        }
        if (root->left == NULL&&root->right == NULL)
        {
            vec.push_back(root->val);
            return vec;
        }
        else
        {
            sta.push(root); //保证左节点先于右节点被访问,根节点后于左右节点被访问
            while (!sta.empty())
            {
                cur = sta.top();            

                if ((cur->left==NULL&&cur->right==NULL)||pre!=NULL&&(pre==cur->left||pre==cur->right))
                { //访问该节点
                    vec.push_back(cur->val);
                    sta.pop();
                    pre = cur;
                }
                else
                {
                    if (cur->right)
                    {
                        sta.push(cur->right);
                    }
                    if (cur->left)
                    {
                        sta.push(cur->left);
                    }
                }
            }
        }
        return vec;
    }
};

145. Binary Tree Postorder Traversal

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8080700.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞