码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode107 Binary Tree Level Order Traversal II

时间:2016-11-05 17:39:10      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:ever   www   from   int   vector   target   tco   html   pop   

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). (Easy)

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]
]

 

分析:

只需要在层序遍历的基础上(参见Binary Tree Level Order Traversal)将最后结果vector reverse即可

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 private:
12     vector<vector<int>> result;
13 public:
14     vector<vector<int>> levelOrderBottom(TreeNode* root) {
15         if (root == nullptr) {
16             return result;
17         }
18         queue<TreeNode* > que;
19         que.push(root);
20         while (!que.empty()) {
21             int sz = que.size();
22             vector<int> temp;
23             for (int i = 0; i < sz; ++i) {
24                 TreeNode* cur = que.front();
25                 que.pop();
26                 temp.push_back(cur -> val);
27                 if (cur -> left != nullptr) {
28                     que.push(cur -> left);
29                 }
30                 if (cur -> right != nullptr) {
31                     que.push(cur -> right);
32                 }
33             }
34             result.push_back(temp);
35         }
36         reverse(result.begin(), result.end());
37         return result;
38     }
39 };

 

LeetCode107 Binary Tree Level Order Traversal II

标签:ever   www   from   int   vector   target   tco   html   pop   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6033481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!