首页 > 代码库 > Leetcode:Binary Tree Level Order Traversal II

Leetcode: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,#,#,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> > result;        if(root == NULL) return result;                vector<vector<TreeNode *> > levels;        vector<TreeNode *> prev(1, root);                while(!prev.empty()){            levels.push_back(prev);            vector<TreeNode *> cur;            for(auto i = prev.begin(); i != prev.end(); i++){                if((*i)->left) cur.push_back((*i)->left);                if((*i)->right) cur.push_back((*i)->right);            }            prev = cur;        }                for(auto i = levels.rbegin(); i != levels.rend(); i++){            vector<int> tmp;            for(auto j = i->begin(); j != i->end(); j++)                tmp.push_back((*j)->val);            result.push_back(tmp);        }                return result;    }};

 

Leetcode:Binary Tree Level Order Traversal II