lintcode-dfs实现二叉树的层序遍历

 1 class Solution {
 2     /**
 3      * @param root: The root of binary tree.
 4      * @return: Level order a list of lists of integer
 5      */
 6     struct node{
 7         TreeNode* tn;
 8         int cnt;
 9         node(TreeNode* tn, int cnt){
10                 this->tn = tn;
11                 this->cnt = cnt;
12         }
13     };
14 
15 public:
16     void dfs(vector<vector<int>> &ans, queue<node*> &que){
17             if(que.empty()) return ;
18             node* now = que.front();
19             que.pop();
20 
21             if(now->tn->left) que.push(new node(now->tn->left, now->cnt + 1));
22             if(now->tn->right) que.push(new node(now->tn->right, now->cnt + 1));
23             
24             if((int)ans.size() - 1 < now->cnt){
25                 vector<int> v(1,now->tn->val);
26                 ans.push_back(v);
27 
28             } else {
29                 ans[now->cnt].push_back(now->tn->val);
30             }
31 
32             dfs(ans, que);
33 
34     }
35     vector<vector<int>> levelOrder(TreeNode *root) {
36         // write your code here
37         vector<vector<int>> ans;
38         if(root == NULL) return ans;
39         queue<node*> que;
40         que.push(new node(root,0));
41         dfs(ans, que);
42         return ans;
43     }
44 };

 

转载于:https://www.cnblogs.com/GeniusYang/p/6975062.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值