# missjing/leetcode

Switch branches/tags
Nothing to show
Fetching contributors…
Cannot retrieve contributors at this time
68 lines (60 sloc) 1.17 KB
 problem： 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 7 return 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. ------------------------------------------------------------------------------------- solution： //层序遍历，用队列作辅助空间 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector > levelOrder(TreeNode *root) { vector > ret; if(root == NULL) return ret; queue q; q.push(root); vector tmp(0); int count = 1; int level = 0; while(!q.empty()) { tmp.clear(); level = 0; for(int i = 0; i < count; ++i) { root = q.front(); q.pop(); tmp.push_back(root->val); if(root->left != NULL) { q.push(root->left); level++; } if(root->right != NULL) { q.push(root->right); level++; } } ret.push_back(tmp); count = level; } return ret; }