博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LC.298.Binary Tree Longest Consecutive Sequence
阅读量:6909 次
发布时间:2019-06-27

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

https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/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,    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,not3-2-1, so return 2. PATH 还是从头走到能走的, 不是从半路 开始走 如果 不满足条件 把当前的MAX = 1 HELPER 函数想到了,全局变量想到了,helper 和 主函数的关系这块儿还需要多做题 time: o(n) space: o(n)
1  int res =0; 2     public int longestConsecutive(TreeNode root) { 3         if (root == null) return res; 4         helper(root,0,root.val); 5         return res ; 6     } 7  8     private void helper(TreeNode root, int max, int target) { 9         //corner case10         if (root == null) return ;11         if (root.val == target){12             max++;13         } else{14             max = 1 ;15         }16         //这里很巧妙的随时更新 RES 这样就不需要HELPER 函数弄返回值17         res = Math.max(res, max) ;18         //细节: MAX 这里是 INT 不是 REF 所以不需要像PATH SUM II 里面 最后一步要 REMOVE19        //换句话说,如果 Max= 2  先走LEFT, left只是对它那一层的 Max 进行改变,20         // 沿着左边走到最后 跳出后,走RIGHT 时,MAX 还是 2!!!21         helper(root.left,max, root.val+1);22         helper(root.right,max, root.val+1);23     }

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8487147.html

你可能感兴趣的文章
cmp()
查看>>
Git系列四之在本地服务器搭建gitlab仓库管理
查看>>
【附6】hystrix metrics and monitor
查看>>
理解linux安装软件
查看>>
php把数组、字符串 生成文件
查看>>
ionic 布局
查看>>
HashMap原理阅读
查看>>
golang 详解defer
查看>>
洗脑是什么
查看>>
MySQL表名大小写敏感导致的问题
查看>>
FastJSON 简单使用
查看>>
jdk目录详解及其使用方法
查看>>
mysql reset password重置密码
查看>>
[转]DOM 中 Property 和 Attribute 的区别
查看>>
Android在一个应用程序中启动另一个应用程序
查看>>
『原创』c#制作的号码mask程序
查看>>
一起谈.NET技术,Unobtrusive JavaScript in ASP.NET MVC 3
查看>>
HTTP长连接和短连接
查看>>
LoaderManager使用详解(二)---了解LoaderManager
查看>>
PHP——0128练习相关2——js点击button按钮跳转到另一个新页面
查看>>