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.queue 的STL 注意是push 跟front 還有pop
reverse也是STL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * 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>> ans;//initial ,empty queue<TreeNode*> parse; if(root==NULL)return ans; parse.push(root); while(parse.size()>0){ vector<int> level;//local level for(int i=parse.size();i>0;i--){ TreeNode * front = parse.front(); level.push_back(front->val); if(front->left!=NULL)parse.push(front->left); if(front->right!=NULL)parse.push(front->right); parse.pop(); } ans.push_back(level); } reverse(ans.begin(),ans.end()); } }; |
---------------------------
recursive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution { public: vector< vector<int> > result; void dfs(TreeNode *root, int level) { if(!root) return; if(level == result.size()) result.push_back( vector<int>() ); vector<int> &vec = result[level]; vec.push_back(root->val); dfs(root->left, level+1); dfs(root->right, level+1); } vector<vector<int>> levelOrderBottom(TreeNode* root) { if(!root) return vector< vector<int> >(); dfs(root, 0); return vector< vector<int> >(result.rbegin(), result.rend()); } }; |
沒有留言:
張貼留言