LeetCode-Binary Tree Level Order Traversal II

/**
 * Definition for binary tree
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > ans;
        if (root == NULL)
        {
            return ans;
        }
        TreeNode *ptr = NULL;
        TreeNode *pEnd = root;
        queue<TreeNode *> q;
        q.push(root);
        vector<int> vec;
        while (!q.empty())
        {
            ptr = q.front();
            q.pop();
            vec.push_back(ptr->val);
            if (ptr->left != NULL)
            {
                q.push(ptr->left);
            }
            if (ptr->right != NULL)
            {
                q.push(ptr->right);
            }
            if (ptr == pEnd)
            {
                ans.push_back(vec);
                vec.clear();
                pEnd = q.back();
            }
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

發佈了124 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章