博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode Binary Tree Level Order Traversal II
阅读量:6920 次
发布时间:2019-06-27

本文共 1494 字,大约阅读时间需要 4 分钟。

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:

Given binary tree {3,9,20,#,#,15,7},

3   / \  9  20    /  \   15   7

 

return its bottom-up level order traversal as:

[  [15,7],  [9,20],  [3]]

 

confused what "{1,#,2,3}" means?

 

这道题目,我想了一天= =

题外话:昨天南京突然降温,超级冷,再加之前天晚上失眠,头脑不太清楚,所以,想这道题想了很久,就是想不对。

想不对的时候乱改一通,又浪费时间又懊丧。

今早真的觉得自己就要做不出来了,后来还是在自己的基础上改对了。

 

我用的方法就是层序遍历+逆序。

层序遍历的时候,我用了一个int值来计每层有多少节点,来判断什么时候得到一个vector。什么时候清空。

思考很重要,耐心很重要。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector
> levelOrderBottom(TreeNode* root) { vector
> result; if(root==NULL) return result; queue
Tree1; int count=1,thiscount=0; TreeNode* p; Tree1.push(root); vector
vtree; while(!Tree1.empty()){ p=Tree1.front(); vtree.push_back(p->val); count--; Tree1.pop(); if(p->left!=NULL){ Tree1.push(p->left); thiscount++; } if(p->right!=NULL){ Tree1.push(p->right); thiscount++; } if(count==0){ result.push_back(vtree); vtree.clear(); count=thiscount; thiscount=0; } } reverse(result.begin(),result.end()); return result; }};

 

转载于:https://www.cnblogs.com/LUO77/p/4993952.html

你可能感兴趣的文章
PreparedStatement 用问号传参引发查询(SQLServer )数据慢的解决方案
查看>>
CAS 单点登录碰到问题汇总
查看>>
Java异常处理最佳实践及陷阱防范
查看>>
mysql报错 could not fetch initial value for incre...
查看>>
zabbix 微信api告警调用
查看>>
VS2008模板遗失问题(转载孙焱的博客)
查看>>
Laravel5.2之Filesystem源码解析(上)
查看>>
PHP PSR-1 基本代码规范(中文版)
查看>>
PHP判断缓存文件是否修改的方法
查看>>
brew安装amp需要注意的点
查看>>
sizeof与strlen的区别
查看>>
快嘉开发框架脚手架及使用说明v1
查看>>
laravel 自带Auth多用户认证
查看>>
linux free
查看>>
Spring RedisTemplate操作-通道操作(10)
查看>>
Redis笔记系列(二)——Redis安装部署与维护详解
查看>>
Hibernate 持久化上下文总结
查看>>
XPath 与多线程爬虫
查看>>
MariaDB 很酷
查看>>
input和span对齐__笔记
查看>>