标签:
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.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode* root) { 13 queue<TreeNode*> que; 14 vector<vector<int>> ret; 15 if(!root) return ret; 16 int cur,next; 17 que.push(root); 18 cur = 1;next = 0; 19 vector<int> tmp; 20 while(!que.empty()) 21 { 22 TreeNode* tmpNode; 23 tmpNode = que.front(); 24 tmp.push_back(tmpNode->val); 25 que.pop(); 26 cur--; 27 if(tmpNode->left) { que.push(tmpNode->left); next++; } 28 if(tmpNode->right) { que.push(tmpNode->right); next++; } 29 if(cur == 0) { cur = next; next = 0; ret.push_back(tmp); tmp.clear(); } 30 31 } 32 33 return ret; 34 } 35 };
(leetcode)Binary Tree Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4835307.html