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

[LeetCode]Binary Tree Level Order Traversal II

时间:2015-09-15 00:00:24      阅读:388      评论:0      收藏:0      [点我收藏+]

标签:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

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 public:
12     void bfs(TreeNode* root,int level,vector<vector<int>>& result)
13     {
14         if(!root) return;
15         if(level>result.size()) result.push_back(vector<int>());
16         result[level-1].push_back(root->val);
17         bfs(root->left,level+1,result);
18         bfs(root->right,level+1,result);
19     }
20     vector<vector<int>> levelOrderBottom(TreeNode* root) {
21         vector<vector<int>> result;
22         bfs(root,1,result);
23         reverse(result.begin(),result.end());
24         return result;
25     }
26 };

 

[LeetCode]Binary Tree Level Order Traversal II

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4808787.html

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