LeetCode 107 Binary Tree Level Order Traversal II

本文提供了一种从下到上遍历二叉树各层节点值的解决方案。通过使用栈来逆序存储每层节点值,最终实现题目要求的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 107

Binary Tree Level Order Traversal II

/**
 * 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<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>>result;
        stack<vector<int>>result1;
        if (root == NULL)
            return result;
        TreeNode* node[3000];
        vector<int> num;
        num.push_back(root->val);
        result1.push(num);
        num.clear();
        int front = -1, rear = -1;
        int last = 0;
        node[++rear] = root;
        while(front<rear) {
            TreeNode* temp = node[++front];
            if (temp->left) {
                node[++rear] = temp->left;
                num.push_back(temp->left->val);
            }
            if (temp->right) {
                node[++rear] = temp->right;
                num.push_back(temp->right->val);
            }
            if (front == last) {
                if(!num.empty()) {
                    result1.push(num);
                    num.clear();
                    last = rear;
                }
            }
        }
        while(!result1.empty()) {
            result.push_back(result1.top());
            result1.pop();
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值