Breadth-first Search - Easy Level - Question 1
Leetcode 101 Binary Tree Level Order Traversal
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
Analysis:
This question is pretty-straightforward: starting with the root, then layer-by-layer goes down.
1. If use a queue, need to know the number of nodes in the current nodes;
2. for each node at one layer, record the node value, then save its child leaves if exist.
See the code below:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode *> q;
q.push(root);
while(!q.empty()) {
vector<int> level;
int k = q.size();
for(int i=0; i<k; ++i) {
auto t = q.front();
q.pop();
level.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(level);
}
return res;
}
};
Comments
Post a Comment