码迷,mamicode.com
首页 > 其他好文 > 详细

[102] Binary Tree Level Order Traversal

时间:2020-04-07 09:36:40      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:efi   vector   val   tree   closed   splay   tor   spl   div   

要求

  • 对二叉树进行层序遍历

实现

技术图片
 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 };
View Code

相关

  • 107 Binary Tree Level Order Traversal II
  • 103 Binary Tree Zigzag Level Order Traversal 
  • 199 Binary Tree Right Side View

[102] Binary Tree Level Order Traversal

标签:efi   vector   val   tree   closed   splay   tor   spl   div   

原文地址:https://www.cnblogs.com/cxc1357/p/12651224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!