题目描述:

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

解题思路:

这题我的想法是遍历每一个节点,把每个节点的数都加到相应层数的一维数组,最后再将二维数组反转。

代码:

 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 createArray(TreeNode* cur,int depth,vector<vector<int>>& array){
13     //3个形参,cur就不用说了,depth用来计算层数,array用来引用result
14         if(!cur)
15             return;
16         if(depth==array.size()){
17         //新的一层就加一个一维数组
18             vector<int> temp;
19             array.push_back(temp);
20         }
21         array[depth].push_back(cur->val);//添加
22         createArray(cur->left,depth+1,array);
23         createArray(cur->right,depth+1,array);
24     }
25     vector<vector<int>> levelOrderBottom(TreeNode* root) {
26         vector<vector<int>> result;
27         createArray(root,0,result);
28         return vector<vector<int>>(result.rbegin(), result.rend());//反转结果
29     }
30 };

 

 

 

posted on 2018-02-08 20:17  宵夜在哪  阅读(83)  评论(0编辑  收藏  举报