[leetcode] 298. Binary Tree Longest Consecutive Sequence 解题报告
2016-03-14 05:44
513 查看
题目链接: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
Longest consecutive sequence path is
so return
Longest consecutive sequence path is
so return
思路: 比较基础的一个DFS, 维护一个当前的连续长度和一个全局最大长度, 每一个往左右子树搜索的时候看是不是正好大一, 然后更新两个变量.
代码如下:
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
1 \ 3 / \ 2 4 \ 5
Longest consecutive sequence path is
3-4-5,
so return
3.
2 \ 3 / 2 / 1
Longest consecutive sequence path is
2-3,not
3-2-1,
so return
2.
思路: 比较基础的一个DFS, 维护一个当前的连续长度和一个全局最大长度, 每一个往左右子树搜索的时候看是不是正好大一, 然后更新两个变量.
代码如下:
/** * 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: void DFS(TreeNode* root, int pre, int len, int& Max) { if(!root) return; len = (root->val==pre+1)?len+1:1; Max = max(Max, len); DFS(root->left, root->val, len, Max); DFS(root->right, root->val, len, Max); } int longestConsecutive(TreeNode* root) { if(!root) return 0; int Max = 1; DFS(root, root->val, 0, Max); return Max; } };
相关文章推荐
- 317. Shortest Distance from All Buildings
- iOS开发之本地通知UILocalNotification
- [Getting and Cleaning data] Quiz 1
- 10003---solr查询不使用query analyzer中文分词的问题解决
- 准备.Net转前端开发-WPF界面框架那些事,UI快速实现法
- UIView的常见属性
- 使用UICollectionView实现轮播图的思路
- 利用android提高的的insert,query,update,deleteAPI与execSql,rawQuery函数执行原生的插入,查询,更新,删除语
- Android UI源码解析
- sqoop2增量导入无法指定last value问题解决方法
- ARM Developer Stuite V1.2 (ADS)的设置
- UIView延迟效果做出动画/UIView动画块
- UIViewTranstion动画
- 拼图pintuer去掉响应式的方法
- AMQP――Advanced Message Queuing Protocol(高级消息队列协议)小结
- 用户界面(人机界面)
- 使用RequestBuilder与服务器通讯
- BEA-290074 <Deployment service servlet received file download request for file "security/SerializedSystemIni.dat". The file may exist, but download of this file is not allowed.>
- jsp之request对象
- UI自定义进度条控件