[LeetCode] Binary Tree Longest Consecutive Sequence
2015-10-30 16:55
495 查看
Problem Description:
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
Longest consecutive sequence path is
This post shares an elegant C++ solution, just in 4 lines. The code is as follows.
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.
This post shares an elegant C++ solution, just in 4 lines. The code is as follows.
/** * 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: int longestConsecutive(TreeNode* root) { return longest(root, NULL, 0); } private: int longest(TreeNode* now, TreeNode* parent, int len) { if (!now) return len; len = (parent && now->val == parent->val + 1) ? len + 1 : 1; return max(len, max(longest(now->left, now, len), longest(now->right, now, len))); } };
相关文章推荐
- UUID of GATT service
- UIScrollView
- 亚博 Arduino智能小车实验报告
- java String StringBuilder StringBuffer 以及各种赋值和注意
- MIT算法导论——第四讲.Quicksort
- MIT算法导论——第三讲.The Divide-and-Conquer
- UISwitch简单用法和监听动画(类似QQ电话)实时显示
- JSP EL表达式 param、paramValues的使用
- [置顶] 【android】音乐播放器之UI设计的点点滴滴
- java中的合并流SequenceInputStreamDemo
- HDU 1711 Number Sequence(KMP模板)
- druid配置
- UE4 Asynchronous Asset Loading
- EAS BOS序时簿Query显示前字段值更新
- android5.1_SystemUI启动流程
- UITableview
- uva 11538 Chess Queen
- UITableView Plain下的section取消顶部粘连
- UITableViewCell 的Separator 间隔线
- UITableViewCell 的Separator 间隔线