298. Binary Tree Longest Consecutive Sequence
2017-01-12 05:48
337 查看
最后更新
三刷。
11-Jan-2017
简单的二叉树,没啥技巧可言,DFS..
Time: O(n)
Space: O(depth)
好像就是楞做,记录长度就行了。
判断失败就从0开始。。
iterative比较难啊。。貌似得记录每一个NODE的当时情况,就得有个MAP之类的了。。
先不考虑了 二刷 再说……
二刷。
DFS,不连续了就更新一下。
二刷做的不如一刷好,写得不如一刷简洁。
三刷。
11-Jan-2017
简单的二叉树,没啥技巧可言,DFS..
Time: O(n)
Space: O(depth)
public class Solution { int max = 0; public int longestConsecutive(TreeNode root) { if (root == null) return max; dfs(root, 0); return max; } public void dfs(TreeNode root, int depth) { max = Math.max(max, ++ depth); if (root == null) return; if (root.left == null && root.right == null) return; if (root.left != null) { if (root.val + 1 == root.left.val) { dfs(root.left, depth); } else { dfs(root.left, 0); } } if (root.right != null) { if (root.val + 1 == root.right.val) { dfs(root.right, depth); } else { dfs(root.right, 0); } } } }
好像就是楞做,记录长度就行了。
判断失败就从0开始。。
public class Solution { int max = 0; public int longestConsecutive(TreeNode root) { if(root == null) return 0; helper(root,0); return max; } public void helper(TreeNode root, int c) { max = Math.max(max,c+1); if(root.left == null && root.right == null) return; if(root.left != null) { if(root.val+1 == root.left.val) helper(root.left,c+1); else helper(root.left,0); } if(root.right != null) { if(root.val+1 == root.right.val) helper(root.right,c+1); else helper(root.right,0); } } }
iterative比较难啊。。貌似得记录每一个NODE的当时情况,就得有个MAP之类的了。。
先不考虑了 二刷 再说……
二刷。
DFS,不连续了就更新一下。
二刷做的不如一刷好,写得不如一刷简洁。
public class Solution { int res; public int longestConsecutive(TreeNode root) { if (root == null) return 0; this.res = 1; twoShots(root.left, root.val, 1); twoShots(root.right, root.val, 1); return res; } public void twoShots(TreeNode root, int prev, int num) { res = Math.max(res, num); if (root == null) return; if (root.val == prev + 1) { twoShots(root.left, prev + 1, num + 1); twoShots(root.right, prev + 1, num + 1); } else { twoShots(root.left, root.val, 1); twoShots(root.right, root.val, 1); } } }
相关文章推荐
- 同步队列SynchronousQueue
- Vue学习笔记(4)关于class和style绑定
- Java小程序之服务器的UI实现
- 模拟Vue之数据驱动4
- SStarting MySQL. ERROR! The server quit without updating PID file
- vue-cli · Failed to download repo vuejs-templates?
- Airpal安装部署--PrestoDB的web UI
- ZooKeeper Administrator's Guide(英文快读)
- uilabel常见设置
- web.xml is missing and <failOnMissingWebXml> is set to true
- SoapUI Groovy 功能测试中使用XmlParser解析xml
- Vuex学习
- vue和miniui 一起使用
- UEFI 安装Ubuntu 16.04分区问题
- js获取select的内容和vlaue
- DP (8) -- Is Subsequence,Ugly Number II
- 精美UI动态界面欣赏
- UVA11527Unique Snowflakes(滑动窗口 + set判重 | | map)
- 可拖拽的easyui treegrid
- Leetcode-95.Unique Binary Search Trees II(a representative recursion problem)