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.
層次遍歷利用佇列實現即可
vector<vector<int> > levelOrder(TreeNode *root){ vector<vector<int> > result; if(root == NULL) return result; queue<TreeNode *> que; que.push(root); int cnt = 1; while(!que.empty()){ vector<int> row; int newCnt = 0; while(cnt--){ TreeNode *node = que.front();que.pop(); row.push_back(node->val); if(node->left) {que.push(node->left); newCnt++;} if(node->right) {que.push(node->right); newCnt++;} } cnt = newCnt; result.push_back(row); } return result; }