Binary Tree Longest Consecutive Sequence
Posted codingEskimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
Binary Tree Longest Consecutive Sequence
298. Binary Tree Longest Consecutive Sequence
298. Binary Tree Longest Consecutive Sequence
LeetCode - Binary Tree Longest Consecutive Sequence