首页 > 代码库 > [leetcode] 9. Binary Tree Level Order Traversal
[leetcode] 9. Binary Tree Level Order Traversal
跟第七题一样,把最后的输出顺序换一下就行。。。
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); } }};
[leetcode] 9. Binary Tree Level Order Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。