LeetCode107 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). (Easy)
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] ]
分析:
只需要在层序遍历的基础上(参见Binary Tree Level Order Traversal)将最后结果vector 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 private: 12 vector<vector<int>> result; 13 public: 14 vector<vector<int>> levelOrderBottom(TreeNode* root) { 15 if (root == nullptr) { 16 return result; 17 } 18 queue<TreeNode* > que; 19 que.push(root); 20 while (!que.empty()) { 21 int sz = que.size(); 22 vector<int> temp; 23 for (int i = 0; i < sz; ++i) { 24 TreeNode* cur = que.front(); 25 que.pop(); 26 temp.push_back(cur -> val); 27 if (cur -> left != nullptr) { 28 que.push(cur -> left); 29 } 30 if (cur -> right != nullptr) { 31 que.push(cur -> right); 32 } 33 } 34 result.push_back(temp); 35 } 36 reverse(result.begin(), result.end()); 37 return result; 38 } 39 };