C++ | Leetcode C++题解之第145题二叉树的后序遍历

题目:

题解:

class Solution {
public:
    void addPath(vector<int> &vec, TreeNode *node) {
        int count = 0;
        while (node != nullptr) {
            ++count;
            vec.emplace_back(node->val);
            node = node->right;
        }
        reverse(vec.end() - count, vec.end());
    }

    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if (root == nullptr) {
            return res;
        }

        TreeNode *p1 = root, *p2 = nullptr;

        while (p1 != nullptr) {
            p2 = p1->left;
            if (p2 != nullptr) {
                while (p2->right != nullptr && p2->right != p1) {
                    p2 = p2->right;
                }
                if (p2->right == nullptr) {
                    p2->right = p1;
                    p1 = p1->left;
                    continue;
                } else {
                    p2->right = nullptr;
                    addPath(res, p1->left);
                }
            }
            p1 = p1->right;
        }
        addPath(res, root);
        return res;
    }
};

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-12 06:48:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-12 06:48:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-12 06:48:02       82 阅读
  4. Python语言-面向对象

    2024-06-12 06:48:02       91 阅读

热门阅读

  1. Unity3D MMORPG 主城角色动画控制与消息触发详解

    2024-06-12 06:48:02       31 阅读
  2. wireshark 用LUA二次开发

    2024-06-12 06:48:02       29 阅读
  3. web前端开发应用:深度解析与实用指南

    2024-06-12 06:48:02       31 阅读
  4. 供需采购报价小程序系统

    2024-06-12 06:48:02       27 阅读
  5. uniapp如何实现跳转

    2024-06-12 06:48:02       28 阅读
  6. 解决Apache Doris占用CPU和内存过高

    2024-06-12 06:48:02       30 阅读
  7. 微信小程序写一个录音机

    2024-06-12 06:48:02       29 阅读
  8. Apache Doris 基础 -- 数据表设计(分层存储)

    2024-06-12 06:48:02       27 阅读