102. Binary Tree Level Order Traversal

问题:

求二叉树的层序遍历。

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3:
Input: root = []
Output: []
 
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000

  

Example 1

 

 

解法:BFS(广度优先搜索)

queue:存储每层遍历节点TreeNode*

for遍历一层。

 

代码参考:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<vector<int>> levelOrder(TreeNode* root) {
15         vector<vector<int>> res;
16         queue<TreeNode*> q;
17         if(root) q.push(root);
18         while(!q.empty()) {
19             int sz = q.size();
20             vector<int> curlevel;
21             for(int i=0; i<sz; i++) {
22                 TreeNode* cur = q.front();
23                 q.pop();
24                 curlevel.push_back(cur->val);
25                 if(cur->left) q.push(cur->left);
26                 if(cur->right) q.push(cur->right);
27             }
28             if(!curlevel.empty())res.push_back(curlevel);
29         }
30         return res;
31     }
32 };

 

posted @ 2021-02-24 17:06  habibah_chang  阅读(53)  评论(0编辑  收藏  举报