LeetCode 107: Binary Tree Level Order Traversal II
2015-10-28 11:04
531 查看
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},
return its bottom-up level order traversal as:
解题思路
在 LeetCode 102 的基础上 reverse 一下就可以了。/** * 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<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> result; if (root == NULL) return result; queue<TreeNode *> nodeQueue; nodeQueue.push(root); while (!nodeQueue.empty()) { vector<int> level_values; int level_size = nodeQueue.size(); // Note: 判断每层的元素个数 for (int i = 0; i < level_size; ++i) { TreeNode *front = nodeQueue.front(); nodeQueue.pop(); level_values.push_back(front->val); if (front->left != NULL) nodeQueue.push(front->left); if (front->right != NULL) nodeQueue.push(front->right); } result.push_back(level_values); } // reverse reverse(result.begin(), result.end()); return result; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解