首页 > 代码库 > [leetcode-102-Binary Tree Level Order Traversal]

[leetcode-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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

思路:

与普通层次遍历稍微不一样的地方就是,需要分出每一层的结点数据来。

如果提前知道每一层数据的个数n,那么只需要循环n次即可取出这一层的数据。那么刚好保持队列内一直为同一层的数据即可。

实现如下:

vector<vector<int>> levelOrder(TreeNode* root)
    {
        queue<TreeNode*>que;
        vector<vector<int>>result;
        if (root == NULL)return result;
        que.push(root);
        
        while (!que.empty())
        {
            int size = que.size();//保证que里始终是同一层的数据
            vector<int> temp;
            for (int i = 0; i < size;i++)
            {
                TreeNode* node = que.front();
                que.pop();                
                temp.push_back(node->val);
                if (node->left != NULL)que.push(node->left);
                if (node->right != NULL)que.push(node->right);
            }
            result.push_back(temp);
        }
        return result;
    }

 

[leetcode-102-Binary Tree Level Order Traversal]