leetcode_question_102 Binary Tree Level Order Traversal

时间:2023-03-09 15:28:10
leetcode_question_102 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 7

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]
BFS:
vector<vector<int> > levelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> matrix;
if(root == NULL) return matrix;
vector<int> r;
r.push_back(root->val);
matrix.push_back(r); vector<TreeNode *> path;
path.push_back(root); int count = 1;
while(!path.empty())
{
TreeNode* tn = path.front();
if(tn->left) path.push_back(tn->left);
if(tn->right) path.push_back(tn->right);
path.erase(path.begin());
count--;
if(count==0)
{
vector<int> tmp;
vector<TreeNode*>::iterator it = path.begin();
for(;it != path.end(); ++it)
tmp.push_back((*it)->val);
if(tmp.size() > 0)
matrix.push_back(tmp);
count = path.size();
}
}
return matrix;
}