107. Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:Given binary tree[3,9,20,null,null,15,7],
    3
    / \
   9  20
      / \
    15  7

return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
         vector<vector<int>> arr;
        if(root==NULL)
          return arr;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        {
            int i = 0;
            int height = q.size();
            vector<int> c;
            while(i++<height)
            {
                TreeNode* t = q.front();
                q.pop();
                c.push_back(t->val);
                if(t->left)
                  q.push(t->left);
                if(t->right)
                  q.push(t->right);
            }
            arr.push_back(c);
        }
        int n = arr.size();
        for(int i=0;i<n/2;i++)
        {
            vector<int> temp = arr[i];
            arr[i] = arr[n-1-i];
            arr[n-1-i] = temp;
        }
        return arr;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容