首页 > 代码库 > Binary Tree Longest Consecutive Sequence
Binary Tree Longest Consecutive Sequence
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * @param root the root of binary tree * @return the length of the longest consecutive sequence path */ private static int MAX_LEN = 0; private class ResultType { TreeNode curNode; int len; int maxLen; public ResultType(TreeNode curNode, int len) { this.curNode = curNode; this.len = len; } } public int longestConsecutive(TreeNode root) { // Write your code here findLongestConsecutive(root); return MAX_LEN + 1; } private ResultType findLongestConsecutive(TreeNode root) { if (root == null) { return new ResultType(null, 0); } ResultType left = findLongestConsecutive(root.left); ResultType right = findLongestConsecutive(root.right); if (left.curNode != null && left.curNode.val - 1 == root.val) { left.len += 1; } else { left.len = 0; } if (right.curNode != null && right.curNode.val - 1 == root.val) { right.len += 1; } else { right.len = 0; } if (left.len > MAX_LEN) { MAX_LEN = left.len; } if (right.len > MAX_LEN) { MAX_LEN = right.len; } return new ResultType(root, Math.max(left.len, right.len)); } }
Binary Tree Longest Consecutive Sequence
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。