Author: Xiao Lu
Column: "Leetcode"
Favorite words: The world is more beautiful because of the youth who stand up. —— "People's Daily"
102. Level order traversal of binary tree
102. Level order traversal of binary tree
Given the root node of your binary tree , return a level-order traversalroot
of its node values . (i.e. visit all nodes layer by layer, from left to right)
Example:
Ideas:
Here we use a queue q and levelsize (representing the number of data in the current layer)
At the beginning, we first press a value into q, and the levelsize is 1. When q is not empty, we loop levelsize times, each time we fetch the head of the queue, and then judge whether there are left and right nodes in the fetched element. The words are pushed in, and then the levelsize is updated when the loop ends
code:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*>q;
int levelsize=0;
if(root)
{
q.push(root);
levelsize=1;
}
vector<vector<int>>vv;
while(!q.empty())
{
vector<int>v;
while(levelsize--)
{
TreeNode*front=q.front();
q.pop();
v.push_back(front->val);
if(front->left)
{
q.push(front->left);
}
if(front->right)
{
q.push(front->right);
}
}
levelsize=q.size();
vv.push_back(v);
}
return vv;
}
};
107. Level Order Traversal of Binary Tree II
107. Level Order Traversal of Binary Tree II
topic:
Given the root node of your binary tree , return the bottom-up order traversal ofroot
its node values . (That is, traverse from left to right layer by layer from the layer where the leaf node is located to the layer where the root node is located)
Example:
Ideas:
Same as the previous question, with an extra inversion at the end.
code:
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode*>q;
int levelsize = 0;
if (root)
{
q.push(root);
levelsize = 1;
}
vector<vector<int>>vv;
while (!q.empty())
{
vector<int>v;
while (levelsize--)
{
TreeNode* front = q.front();
q.pop();
v.push_back(front->val);
if (front->left)
{
q.push(front->left);
}
if (front->right)
{
q.push(front->right);
}
}
levelsize = q.size();
vv.push_back(v);
}
reverse(vv.begin(),vv.end());
return vv;
}
};