欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode145. Binary Tree Postorder Traversal(后序遍历)

程序员文章站 2022-05-18 19:39:03
...

145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]

   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?


题目:二叉树的后续遍历,递归的方式。

思路Preorder, Inorder, and Postorder Iteratively Summarization

工程代码下载

/**
 * 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*> nodes;
        vector<int> res;
        while(root != nullptr || nodes.size()){
            if(root != nullptr){
                nodes.push(root);
                res.push_back(root->val);
                root = root->right;
            }
            else{
                TreeNode* node = nodes.top();
                nodes.pop();
                root = node->left;
            }
        }
        reverse(res.begin(), res.end());
        return res;
    }
};
相关标签: tree