leetcode-107. 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,null,null,15,7],

    3
   / 
  9  20
    /  
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

思路:
首先定义一个vector<vector<TreeNode*>> temp来保存二叉树的层次遍历结果,然后将temp中的层次中节点的值倒序赋值给vector<vector<int>> result。

accepted code:
 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     vector<vector<int>> levelOrderBottom(TreeNode* root) {
13         vector<vector<int>> result;
14         vector<vector<TreeNode*>> temp;
15         if(root==nullptr)
16         return result;
17         vector<TreeNode*> tk;
18         tk.push_back(root);
19         temp.push_back(tk);
20         int i=0;
21         while(temp[i].size()>0)
22         {
23             tk.clear();
24             for(int j=0;j<temp[i].size();j++)
25             {
26                 if(temp[i][j]->left!=nullptr)
27                 tk.push_back(temp[i][j]->left);
28                 if(temp[i][j]->right!=nullptr)
29                 tk.push_back(temp[i][j]->right);
30             }
31             temp.push_back(tk);
32             i++;
33         }
34         vector<int> num;
35         for(int i=temp.size()-2;i>=0;i--)
36         {
37             for(int j=0;j<temp[i].size();j++)
38             {
39                 num.push_back(temp[i][j]->val);
40             }
41             result.push_back(num);
42             num.clear();
43         }
44         return result;
45     }
46 };

 
原文地址:https://www.cnblogs.com/hongyang/p/6417676.html