[Leetcode] Binary Tree Level Order Traversal

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。

Binary Tree Level Order Traversal 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/binary-tree-level-order-traversal/description/


Description

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

Example

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

Solution


class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if (root == NULL) return res;
        queue<TreeNode*> q1, q2;
        q2.push(root);
        TreeNode* node;
        int i;
        while (!q2.empty()) {
            while (!q2.empty()) {
                node = q2.front();
                q2.pop();
                q1.push(node);
            }
            vector<int> level(q1.size());
            i = 0;
            while (!q1.empty()) {
                node = q1.front();
                q1.pop();
                level[i++] = node -> val;
                if (node -> left != NULL)
                    q2.push(node -> left);
                if (node -> right != NULL)
                    q2.push(node -> right);
            }
            res.push_back(level);
        }
        return res;
    }
};

解题描述

这道题是经典的二叉树层次遍历问题,上面给出的解法使用2个队列,一开始将根节点放入队列q2,进入循环,每次将q2中全部节点出队加入队列q1,再将这些节点的子节点全部加入q2,即可实现层次遍历。

下面再给出一种讨论区的只使用单个队列实现的方法:


class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if (root == NULL) return res;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);  // 每一层结束的标志
        vector<int> level;
        while (!q.empty()) {
            TreeNode* node = q.front();
            q.pop();
            if (node != NULL) {
                level.push_back(node -> val);
                if (node -> left != NULL)
                    q.push(node -> left);
                if (node -> right != NULL)
                    q.push(node -> right);
            } else { // 得到的节点是一层的结束标志NULL,则将当前层数组加入res
                res.push_back(level);
                level.clear();
                if (!q.empty())  // 当前层已经扫描完毕,此时下一层也已经全部加入队列,需要往队列中加入层结束标志NULL
                    q.push(NULL);
            }
        }
        return res;
    }
};

以上是关于[Leetcode] Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] construct-binary-tree-from-inorder-and-postorder-

[LeetCode226]Invert Binary Tree

[Leetcode] Binary tree-- 606. Construct String from Binary Tree

[Leetcode] Binary search tree --Binary Search Tree Iterator

Leetcode[110]-Balanced Binary Tree

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree