随笔 - 0,  文章 - 900,  评论 - 0,  阅读 - 33万

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for binary tree
 * 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> > result;
        if (root == NULL) return result;
         
        queue<TreeNode*> q;
        q.push(root);
         
        while (!q.empty()) {
            int count = q.size();
            result.push_back(vector<int>());
            for (int i = 0; i < count; i++) {
                TreeNode *tmp = q.front();
                q.pop();
                if (tmp->left != NULL) q.push(tmp->left);
                if (tmp->right != NULL) q.push(tmp->right);
                result.back().push_back(tmp->val);
            }
        }
         
        return result;       
    }
};

 

posted on   风云逸  阅读(44)  评论(0)    收藏  举报
(评论功能已被禁用)

点击右上角即可分享
微信分享提示