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 / 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.
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 public: 12 void bfs(TreeNode* root,int level,vector<vector<int>>& result) 13 { 14 if(!root) return; 15 if(level>result.size()) result.push_back(vector<int>()); 16 result[level-1].push_back(root->val); 17 bfs(root->left,level+1,result); 18 bfs(root->right,level+1,result); 19 } 20 vector<vector<int>> levelOrderBottom(TreeNode* root) { 21 vector<vector<int>> result; 22 bfs(root,1,result); 23 reverse(result.begin(),result.end()); 24 return result; 25 } 26 };
时间: 2024-12-09 18:45:49