leetcode: Binary Tree Level Order Traversal II

来源:互联网 发布:jquery 数组遍历 编辑:程序博客网 时间:2024/05/29 10:13

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]]
和I一样,只要插入的时候插入到res的begin()就可以了

/** * 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) {        vector< vector< int> > res;          if( root == NULL)              return res;          vector< int> cur;          queue< pair< TreeNode *, int> > q;          q.push( make_pair( root, 1));          int level = 1;          while( !q.empty()){              pair< TreeNode *, int> tmp = q.front();              q.pop();              if( tmp.first->left)                  q.push( make_pair( tmp.first->left, tmp.second+1));              if( tmp.first->right)                  q.push( make_pair( tmp.first->right, tmp.second+1));              if( tmp.second > level){                  res.insert( res.begin(), cur);                  cur.clear();                  ++level;              }              cur.push_back( tmp.first->val);          }          res.insert( res.begin(), cur);          return res;      }};


0 0