LeetCode 298. Binary Tree Longest Consecutive Sequence(二叉树最长连续序列)
2016-04-17 00:08
447 查看
原题网址: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
方法:递归遍历,递归函数传入父节点的值,以帮助子节点判断是否连续。
优化:
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.
方法:递归遍历,递归函数传入父节点的值,以帮助子节点判断是否连续。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int max = 0; private void find(TreeNode root, int parent, int count) { if (root.val == parent+1) count ++; else count = 1; max = Math.max(max, count); if (root.left != null) find(root.left, root.val, count); if (root.right != null) find(root.right, root.val, count); } public int longestConsecutive(TreeNode root) { if (root == null) return 0; max = 1; if (root.left != null) find(root.left, root.val, 1); if (root.right != null) find(root.right, root.val, 1); return max; } }
优化:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int max = 1; private void find(TreeNode root, int prev, int len) { if (prev+1 == root.val) len ++; else len = 1; max = Math.max(max, len); if (root.left != null) find(root.left, root.val, len); if (root.right != null) find(root.right, root.val, len); } public int longestConsecutive(TreeNode root) { if (root == null) return 0; find(root, 0, 0); return max; } }
相关文章推荐
- HDU 5667 :Sequence
- 第一次接触JS require.js模块化工具
- 第二次聊一聊JS require.js模块化工具的基础知识
- ULabel显示1.n行文字特效,特效
- iOS修改xib中大小已经固定的UI控件的frame
- 自定制UINavigationBar和navigationBarItem
- easyui,datagrid表格显示的字段内容随机
- hdu 5667 Sequence【矩阵快速幂】
- AndroidStudio编译时卡在Gradle Build Running并死机的解决方法
- hdu-4991 Ordered Subsequence(dp+树状数组)
- 修改UITextField的placeholder颜色
- Assurance 4000 Techniques for Industrial Control Systems (ICS)
- Ubiquitous Religions(sdut_2428)
- requirejs 学习
- getRequestURL、getRequestURI、getContextPath、getServletPath和getRealPath的区别
- UI更新方法Handler和runOnUiThread
- UIImage imageName方法扩充提醒功能
- hdu 5667Sequence
- 【Arduino官方教程第一辑】示例程序 1-4 读取数字引脚
- HDU 5667 Sequence