首页 > 代码库 > LeetCode--Binary Tree Level Order Traversal

LeetCode--Binary Tree Level Order Traversal

用两个队列实现,交叉使用,达到判断层的目的

 1 /** 2  * Definition for binary tree 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         vector<vector<int> > res;14         if(root == NULL)15         {16             return res;17         }18         queue<TreeNode *> q1;19         queue<TreeNode *> q2;20         q1.push(root);21         while(!q1.empty() || !q2.empty())22         {23             vector<int> tmpres;24             if(!q1.empty())25             {26                 while(!q1.empty())27                 {28                     TreeNode *tmp = q1.front();29                     q1.pop();30                     tmpres.push_back(tmp->val);31                     if(tmp->left!=NULL)32                     {33                         q2.push(tmp->left);34                     }35                     if(tmp->right!=NULL)36                     {37                         q2.push(tmp->right);38                     }39                 }40             }41             else42             {43                 while(!q2.empty())44                 {45                     TreeNode *tmp = q2.front();46                     q2.pop();47                     tmpres.push_back(tmp->val);48                     if(tmp->left!=NULL)49                     {50                         q1.push(tmp->left);51                     }52                     if(tmp->right!=NULL)53                     {54                         q1.push(tmp->right);55                     }56                 }57             }58             res.push_back(tmpres);59         }60         return res;61     }62 };

 

LeetCode--Binary Tree Level Order Traversal