[Leetcode]|[Leetcode] 87. 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,#,#,15,7},
3
/ \
920
/\
157
return its bottom-up level order traversal as:
【[Leetcode]|[Leetcode] 87. Binary Tree Level Order Traversal II】[
[15,7],
[9,20],
[3]
]
解题之法
/**
* Definition for a binary tree node.
* struct TreeNode {
*int val;
*TreeNode *left;
*TreeNode *right;
*TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector> levelOrderBottom(TreeNode* root) {
vector > res;
levelorder(root, 0, res);
return vector > (res.rbegin(), res.rend());
}
void levelorder(TreeNode *root, int level, vector > &res) {
if (!root) return;
if (res.size() == level) res.push_back({});
res[level].push_back(root->val);
if (root->left) levelorder(root->left, level + 1, res);
if (root->right) levelorder(root->right, level + 1, res);
}
};
推荐阅读
- LeetCode 题解 | 1. 两数之和 Javascript 版
- 220902_leetcode 21. Merge Two Sorted Lists 合并两个有序链表(简单).md
- 687. 最长同值路径 : 简单递归运用题
- leetcode 206. Reverse Linked List 反转链表(简单)
- Leetcode-222题:Count|Leetcode-222题:Count Complete Tree Nodes
- leetcode|【Leetcode】刷题题单记录
- leetcode 242. Valid Anagram 有效的字母异位词(简单)
- leetcode 594. Longest Harmonious Subsequence 最长和谐子序列(简单).md
- leetcode 697. Degree of an Array 数组的度(简单)
- leetcode 503. Next Greater Element II 下一个更大元素 II(中等)