[刷题] 102 Binary Tree Level Order Traversal
要求
- 对二叉树进行层序遍历
实现
- 返回结果为双重向量,对应树的每层元素
- 队列的每个元素是一个pair对,存树节点和其所在的层信息
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Definition for a binary tree node. 2 struct TreeNode { 3 int val; 4 TreeNode *left; 5 TreeNode *right; 6 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 7 }; 8 9 class Solution { 10 public: 11 vector<vector<int>> levelOrder(TreeNode* root) { 12 vector<vector<int>> res; 13 if( root == NULL ) 14 return res; 15 queue< pair<TreeNode*, int> > q; 16 q.push( make_pair( root , 0 ) ); 17 while( !q.empty() ){ 18 TreeNode* node = q.front().first; 19 int level = q.front().second; 20 q.pop(); 21 22 if( level == res.size() ) 23 res.push_back( vector<int>() ); 24 res[level].push_back( node->val ); 25 26 if( node->left ) 27 q.push( make_pair( node->left , level + 1 )); 28 if( node->right ) 29 q.push( make_pair( node->right , level + 1 )); 30 } 31 return res; 32 } 33 };
相关
- 107 Binary Tree Level Order Traversal II
- 103 Binary Tree Zigzag Level Order Traversal
- 199 Binary Tree Right Side View