102 Binary Tree Level Order Traversal 二叉树的层次遍历

Posted lina2014

tags:

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

给定一个二叉树,返回其按层次遍历的节点值。 (即zhu‘ceng‘de,从左到右访问)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果为:
[
  [3],
  [9,20],
  [15,7]
]
详见:https://leetcode.com/problems/binary-tree-level-order-traversal/description/

/**
 * 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>> res;
        if(!root)
        {
            return res;
        }
        queue<TreeNode*> que;
        que.push(root);
        vector<int> out;
        int i=1;
        while(!que.empty())
        {
            root=que.front();
            que.pop();
            --i;
            out.push_back(root->val);
            if(root->left)
            {
                que.push(root->left);
            }
            if(root->right)
            {
                que.push(root->right);
            }
            if(i==0)
            {
                i=que.size();
                res.push_back(out);
                out.clear();
            }
        }
        return res;
    }
};

 

以上是关于102 Binary Tree Level Order Traversal 二叉树的层次遍历的主要内容,如果未能解决你的问题,请参考以下文章

102. Binary Tree Level Order Traversal

LeetCode102. Binary Tree Level Order Traversal

102Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

Leetcode 102. Binary Tree Level Order Traversal

[LeetCode]题解(python):102 Binary Tree Level Order Traversal