按層輸出二叉樹,廣度優先。node
3
/ \
9 20
/ \
15 7
[
[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<vector<int>> rres; void levelTree(TreeNode*root, int level){ if (root == NULL) return; if (level == rres.size()){ vector<int> res; rres.push_back(res); } rres[level].push_back(root->val); levelTree(root->left,level+1); levelTree(root->right,level+1); } vector<vector<int>> levelOrderBottom(TreeNode* root) { levelTree(root,0); //return reverse(rres.begin(),rres.end());
return vector<vector<int> >(rres.rbegin(), rres.rend()); } };