C++ 二叉树的后序遍历 - 力扣(LeetCode)

点击链即可查看题目: 145. 二叉树的后序遍历 - 力扣(LeetCode)

一、题目

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

示例 1:

**输入:**root = 1,null,2,3

输出:3,2,1

解释:

示例 2:

**输入:**root = 1,2,3,4,5,null,8,null,null,6,7,9

输出:4,6,7,5,2,9,8,3,1

解释:

示例 3:

**输入:**root = \[\]

输出:\[\]

示例 4:

**输入:**root = 1

输出:1

提示:

  • 树中节点的数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

二、解题思路以及代码

cpp 复制代码
/**
 * 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<int> postorderTraversal(TreeNode* root) 
    {
        stack<TreeNode*> st;
        vector<int> v;
        TreeNode* prev = nullptr;
        //先访问左路节点
        
        TreeNode* cur = root;
        while(cur || !st.empty())
        {
            while(cur)
            {
                //左路节点访问,并且入栈
                st.push(cur);
                cur = cur->left;
            }
            //取栈顶元素
            TreeNode* top = st.top();
            
            //访问右子树
            //右子树为空   或   prev是top的右,证明右子树已经访问完了
            if(nullptr == top->right || prev == top->right)
            {
                v.push_back(top->val);
                st.pop();
                prev = top;
            }
            else//右子树不为空,并且没有访问
            {
                cur = top->right; 
            }
        }
        return v;
    }
};
相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
weilx12343 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛3 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·3 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法