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] ]
将二叉树每一层的节点放入二维数组中
C++(6ms):
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 if (root == NULL) 14 return vector<vector<int>>() ; 15 vector<vector<int>> res ; 16 queue<TreeNode*> que ; 17 que.push(root) ; 18 while(!que.empty()){ 19 int len = que.size() ; 20 vector<int> vec ; 21 for(int i = 0 ; i < len ; i++){ 22 TreeNode* node = que.front() ; 23 que.pop() ; 24 vec.push_back(node->val) ; 25 if (node->left) 26 que.push(node->left) ; 27 if (node->right) 28 que.push(node->right) ; 29 } 30 res.push_back(vec) ; 31 } 32 reverse(res.begin() , res.end()) ; 33 return res ; 34 } 35 };