天天看点

LeetCode 107 Binary Tree Level Order Traversal IILeetCode 107

LeetCode 107

Binary Tree Level Order Traversal II

  • Problem Description:

    从下到上输出二叉树每一层的节点值

    具体的题目信息:

    https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/

  • Example:
    LeetCode 107 Binary Tree Level Order Traversal IILeetCode 107
  • Solution:
/**
 * 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;
    }
};