1. 题目

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

2. 思路

用FIFO队列来构建水平遍历。用NULL来分割不同的层。

3. 代码

/**
 * 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>> ret;
        if (root == NULL) { return ret; }
        vector<int> level;
        deque<TreeNode*> d;
        d.push_back(root);
        d.push_back(NULL);
        while (!d.empty()) {
            TreeNode* n = d.front();
            d.pop_front();
            if (n == NULL) {
                if (level.size() != 0) {
                    ret.push_back(level);
                    level.clear();
                }
                if (d.empty()) { return ret; }
                else { d.push_back(NULL); }
            } else {
                if (n->left != NULL) {
                    d.push_back(n->left);
                }
                if (n->right != NULL) {
                    d.push_back(n->right);
                }
                level.push_back(n->val);
            }
        }
        return ret;
    }
};

knzeus
72 声望28 粉丝

行万里路,读万卷书