跟第七题一样,把最后的输出顺序换一下就行。。。
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For example:
Given binary tree{3,9,20,#,#,15,7}
,3 / 9 20 / 15 7return its level order traversal as:
[ [3], [9,20], [15,7] ]confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
题解如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int>> temp; int len = MaxDepth(root); for (int i = 0; i < len; i++) { vector<int> level; getElement(level, 0, i, root); temp.push_back(level); level.clear(); } return temp; } int MaxDepth(TreeNode *temp) { if (temp == NULL) return 0; else { int aspros = MaxDepth(temp->left); int defteros = MaxDepth(temp->right); return 1 + (aspros>defteros ? aspros : defteros); } } void getElement(vector<int> &level, int count, int len, TreeNode *root) { if (root != NULL) { if (count == len) { level.push_back(root->val); } getElement(level, count + 1, len, root->left); getElement(level, count + 1, len, root->right); } } };
时间: 2024-10-19 14:48:26