LeetCode 102. Binary Tree Level Order Traversal

题意:给定一棵树,求其层序遍历序列。(以vector<vector<int>>形式返回)

解题思路:

  1. 通过num1和num2来记录当前层还有多少结点,下一层有多少结点;
  2. 注意为空树的情况。
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrder(TreeNode* root) {
13         queue<TreeNode*> q;
14         vector<vector<int>> v;
15         q.push(root);
16         vector<int> vv; 
17         int num1=1,num2=0;
18         
19         while(root!=NULL && !q.empty()){
20             TreeNode* tmp=q.front();
21             q.pop();
22             vv.push_back(tmp->val);
23             num1--;
24             
25             if(tmp->left!=NULL){
26                 q.push(tmp->left);
27                 num2++;
28             }
29             if(tmp->right!=NULL){
30                 q.push(tmp->right);
31                 num2++;
32             }
33 
34             // 该层元素全部遍历完毕
35             if(num1==0){
36                 v.push_back(vv);
37                 vv.clear();
38                 num1=num2;
39                 num2=0;
40             }
41         }
42 
43         return v;
44     }
45 };
原文地址:https://www.cnblogs.com/yy-1046741080/p/11626910.html