linus_Robot的博客

渣渣的成长之路

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]
]

/**二叉树的bfs和队列个数,可分层处理到每一层的的节点。
 * Definition for a binary tree node.
 * 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> > outer;
        vector<int> inner;
        queue<TreeNode*> q;
        if (root)
            q.push(root);
        else
            return outer;
        while (!q.empty())
        {
            int size=q.size();//当前队列的个数,用来将当前层的节点全从队列中移除。
            inner.clear();
            while (size-->0)
            {
                TreeNode* t=q.front();
                q.pop();
                inner.push_back(t->val);
                if (t->left)
                   q.push(t->left);
                if (t->right)
                   q.push(t->right);
            }
            outer.push_back(inner);
        }
        return outer;
    }
  
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26399665/article/details/52371982
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭