码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Binary Tree Level Order Traversal(层序遍历)

时间:2015-06-24 16:30:04      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:leetcode   levelorder   

Question

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,#,#,15,7},

    3
   /   9  20
    /     15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Solution

/**
 * 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>> out_vec;
        vector<int> vec;
        if(root == NULL)
            return out_vec;
        queue<TreeNode*> que;
        que.push(root);
        int level = 0;
        int num = 1;
        while(!que.empty())
        {
            vec.clear();
            level = 0;
            for(int i = 0; i < num; i ++)
            {
                root = que.front();
                que.pop();
                vec.push_back(root->val);
                if(root->left != NULL)
                {
                    que.push(root->left);
                    level ++;
                }

                if(root->right != NULL)
                {
                    que.push(root->right);
                    level ++;
                }

            }

            num = level;
            out_vec.push_back(vec);

        }
        return out_vec;

    }
};

【LeetCode】Binary Tree Level Order Traversal(层序遍历)

标签:leetcode   levelorder   

原文地址:http://blog.csdn.net/zwhlxl/article/details/46622619

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!