【leetcode】102. Binary Tree Level Order Traversal 水平遍历二叉树

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
    原文地址: https://segmentfault.com/a/1190000007458894
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞