(二叉树 BFS) 102. Binary Tree Level Order Traversal
Posted weixu-liu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(二叉树 BFS) 102. Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。
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] ]
-----------------------------------------------------------------------------
就是遍历二叉树的的每一层,并且把每一层的数加入到一个数组,返回这个二维数组。
C++代码:
/** * 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) { queue<TreeNode*> q; vector<int> vec; vector<vector<int> > vecs; if(!root){ return vecs; //这个vecs指的是空数组。 } q.push(root); while(!q.empty()){ vec.clear(); for(int i = q.size();i>0;i--){ auto t = q.front(); q.pop(); vec.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } vecs.push_back(vec); } return vecs; } };
以上是关于(二叉树 BFS) 102. Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode102. Binary Tree Level Order Traversal-二叉树水平顺序遍历
102 Binary Tree Level Order Traversal 二叉树的层次遍历
LeetCode 102 Binary Tree Level Order Traversal(二叉树的层级顺序遍历)(*)