⭐算法OJ⭐二叉树的后序遍历【树的遍历】(C++实现)Binary Tree Postorder Traversal

⭐算法OJ⭐二叉树的中序遍历【树的遍历】(C++实现)Binary Tree Inorder Traversal
⭐算法OJ⭐二叉树的前序遍历【树的遍历】(C++实现)Binary Tree Preorder Traversal

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

Example 1:

复制代码
Input: root = [1,null,2,3]
Output: [3,2,1]

Explanation:

Example 2:

复制代码
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,6,7,5,2,9,8,3,1]

Explanation:

Example 3:

复制代码
Input: root = []
Output: []

Example 4:

复制代码
Input: root = [1]
Output: [1]
cpp 复制代码
// 定义二叉树节点
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

递归解法

  • 后序遍历的顺序是:左子树 → \rightarrow → 右子树 → \rightarrow → 根节点。
  • 使用递归实现。
cpp 复制代码
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result; // 存储遍历结果
        postorder(root, result); // 递归遍历
        return result;
    }

private:
    void postorder(TreeNode* node, vector<int>& result) {
        if (node == nullptr) {
            return; // 递归终止条件
        }
        postorder(node->left, result); // 遍历左子树
        postorder(node->right, result); // 遍历右子树
        result.push_back(node->val); // 访问根节点
    }
};

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n 是二叉树的节点数。每个节点被访问一次。
  • 空间复杂度: O ( h ) O(h) O(h),其中 h h h 是二叉树的高度。递归调用栈的深度取决于树的高度。

迭代解法(使用栈)

  • 使用 模拟递归过程。
  • 每次从栈中弹出一个节点,将其值插入结果列表的开头。
  • 先压入左子树,再压入右子树,以确保右子树先被处理。从根节点开始,先将所有左子节点入栈,然后访问节点,再转向右子树。
cpp 复制代码
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        if (root == nullptr) {
            return result;
        }
        stack<TreeNode*> stk;
        stk.push(root);
        while (!stk.empty()) {
            TreeNode* node = stk.top();
            stk.pop();
            result.insert(result.begin(), node->val); // 将节点值插入结果的开头
            if (node->left) {
                stk.push(node->left); // 先压入左子树
            }
            if (node->right) {
                stk.push(node->right); // 再压入右子树
            }
        }
        return result;
    }
};
相关推荐
Tim_10几秒前
【算法专题训练】20、LRU 缓存
c++·算法·缓存
Vect__14 分钟前
从零实现一个简化版string 类 —— 深入理解std::string的底层设计
c++
hope_wisdom17 分钟前
C/C++数据结构之栈基础
c语言·数据结构·c++··stack
青铜发条18 分钟前
【Qt】PyQt、原生QT、PySide6三者的多方面比较
开发语言·qt·pyqt
ajassi200025 分钟前
开源 C++ QT Widget 开发(十四)多媒体--录音机
linux·c++·qt·开源
B612 little star king39 分钟前
力扣29. 两数相除题解
java·算法·leetcode
野犬寒鸦41 分钟前
力扣hot100:环形链表(快慢指针法)(141)
java·数据结构·算法·leetcode·面试·职场和发展
时光追逐者1 小时前
C# 哈希查找算法实操
算法·c#·哈希算法
Jasmine_llq1 小时前
《P3825 [NOI2017] 游戏》
算法·游戏·枚举法·2-sat 算法·tarjan 算法·邻接表存储
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展