binary-tree-postorder-traversal(leetcodee)

题目描述

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) {}
 * };
 */
#include<algorithm>
#include<vector>

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int>res;
        if (!root)
            return res;
        //根左右-->根右左-->左右根
        stack<TreeNode*> Stk;
        Stk.push(root);
        TreeNode *temp;
        while(Stk.size())
        {
           //根左右顺序压栈
            temp = Stk.top();
                Stk.pop();
            res.push_back(temp -> val);
            if(temp -> left)
                Stk.push(temp -> left);
            if(temp -> right)
                Stk.push(temp -> right);
        }
        //根右左逆转
        reverse(res.begin(),res.end());
        
        return res; 
    }
};

在这里插入图片描述
2. qq

原文链接:加载失败,请重新获取