标签:binary tree level order traversa bottom_to_root leetcode
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 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
此题与LeetCode 101 Binary Tree Level Order Traversal,一样都是二叉树的层次遍历,不同的是这一次是从叶子,到根节点。所以只需要在LeetCode101的基础上再做一次翻转即可。代码如下:
class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { //同二叉树的层次遍历 vector<vector<int>>result; if (!root) return result; queue<TreeNode*> vec; vec.push(root); while (vec.size() > 0) { queue<TreeNode*> tmp_vec; vector<int> tmp_result; while (vec.size() > 0) { TreeNode* node = vec.front(); vec.pop(); if (node->left) tmp_vec.push(node->left); if (node->right) tmp_vec.push(node->right); tmp_result.push_back(node->val); } vec = tmp_vec; result.push_back(tmp_result); } //对层次遍历结果进行翻转 reverse(result.begin(), result.end()); return result; } };
LeetCode 107:Binary Tree Level Order Traversal II
标签:binary tree level order traversa bottom_to_root leetcode
原文地址:http://blog.csdn.net/sunao2002002/article/details/46280539