leetcode 107. Hierarchical Traversal of Binary Trees II

Given a binary tree, return the bottom-up level traversal of its node values. (That is, from the layer where the leaf node is located to the layer where the root node is located, traversing layer by layer from left to right)

For example:
given a binary tree  [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

Return its bottom-up level 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 #include<algorithm>
11 class Solution {
12 public:
13     vector<vector<int>> levelOrderBottom(TreeNode* root) {
14         queue<TreeNode*> q;
15         q.push(root);
16         vector<vector<int>> ans;
17         if(root == NULL) return ans;
18         while(!q.empty()){
19             queue<TreeNode*> qt;
20             vector<int> t;
21             while(!q.empty()){
22                 TreeNode* temp = q.front();
23                 q.pop();
24                 t.push_back(temp->val);
25                 if(temp->left) qt.push(temp->left);
26                 if(temp->right) qt.push(temp->right);
27             }
28             ans.push_back(t);
29             q = qt;
30         }
31         reverse(ans.begin(), ans.end());
32         return ans;
33     }
34 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325150282&siteId=291194637