栈模拟递归,LeetCode 145. 二叉树的后序遍历

一、题目

1、题目描述

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 

2、接口描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector postorderTraversal(TreeNode* root) {

    }
};

3、原题链接

145. 二叉树的后序遍历


二、解题报告

1、思路分析

用栈模拟递归即可,先往左走,然后往右走,往根回溯的条件为右路为空或者右路访问过

2、复杂度

时间复杂度: O(N)空间复杂度:O(N)

3、代码详解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
TreeNode* s[105], *last;
int t;
    vector postorderTraversal(TreeNode* root) {
        vector ret;
        last = nullptr;
        while(t || root){
            while(root)
                s[t++] = root, root = root -> left;
            if(last == s[t - 1] -> right || !s[t - 1] -> right)
                ret.emplace_back((last = s[--t]) -> val);
            else root = s[t - 1]->right;
        }
        return ret;
    }
};

你可能感兴趣的:(leetcode每日一题,算法,c++,leetcode,数据结构)