# Binary Tree Level Order Traversal

Oct 24, 2017

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,null,null,15,7],

    3
/ \
9  20
/  \
15   7


return its level order traversal as:

[
[3],
[9,20],
[15,7]
]


emmm，简单来讲就是层次遍历.

• 先让root入队，这时我们队列里面就有第一层的所有元素了
• 我们记录当前层次所拥有的元素的个数size，然后出队size个元素，对于每一个出队的元素，我们遍历它一次，然后将它的左右孩子入队。
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > ret;
if (root == NULL) return ret;
queue<TreeNode *> q;
q.push(root);
int size = 0;
int last = 0;
while((size = q.size())) {
ret.push_back(vector<int>());
while(size--) {
root = q.front();
q.pop();
ret[last].push_back(root->val);
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
last++;
}
return ret;
}


vector<vector<int> > ret;
vector<vector<int>> levelOrder(TreeNode* root) {
leverlOrder(root,0);
return ret;
}
void levelOrder(TreeNode* root,int level) {
if (root==NULL)
return;
if (level >= ret.size() ) {
ret.push_back(vector<int>());
}
ret[level].push_back(root->val);
levelOrder(root->left,level+1);
levelOrder(root->right,level+1);
}


LeetCodeLeetCodeTree

Construct Binary Tree from Preorder and Inorder Traversal

Validate Binary Search Tree