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]
]
思路:
这个跟leetcode-102-Binary Tree Level Order Traversal 其实差不多的。
唯一不同的是在每一层遍历完之后,得到本层的数值,插入到最终result数组里的时候从头插入,即可实现倒序。
vector<vector<int>> levelOrderBottom(TreeNode* root) { queue<TreeNode*>que; vector<vector<int>>result; if (root == NULL)return result; que.push(root); while (!que.empty()) { int size = que.size(); vector<int> temp; for (int i = 0; i < size; i++) { TreeNode* node = que.front(); que.pop(); temp.push_back(node->val); if (node->left != NULL)que.push(node->left); if (node->right != NULL)que.push(node->right); } result.insert(result.begin(), temp);//从头部插入即可实现倒序 } return result; }