美文网首页
[leetcode] 102. Binary Tree Leve

[leetcode] 102. Binary Tree Leve

作者: 叶孤陈 | 来源:发表于2017-06-10 19:45 被阅读0次

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

    解题思路:
    本题让我们求解数的宽度优先遍历,具体思路有使用队列将每一层的节点保存下来,然后按照FIFO的选择逐个遍历,然后将每个节点的子节点存入队列,以此类推。

    具体代码如下:

    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> ret;
            queue<TreeNode*> level;
            if(!root) return ret;
            level.push(root);
            
            while(!level.empty())
            {
                vector<int> curLevel;
                int size = level.size();
                for(int i = 0; i < size; ++i)
                {
                    TreeNode* curr = level.front();
                    curLevel.push_back(curr->val);
                    level.pop();
                    if(curr->left) level.push(curr->left);
                    if(curr->right) level.push(curr->right);
                }
                ret.push_back(curLevel);
            }
            return ret;
        }
    };
    

    相关文章

      网友评论

          本文标题:[leetcode] 102. Binary Tree Leve

          本文链接:https://www.haomeiwen.com/subject/bndcqxtx.html