本文主要是介绍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 {int max = 1;public int longestConsecutive(TreeNode root) {if (root == null) {return 0;}helper(root, 1);return max;}private void helper(TreeNode node, int num) {if (node.left != null) {if (node.val + 1 == node.left.val) {max = Math.max(max, num + 1);helper(node.left, num + 1);} else {helper(node.left, 1);}}if (node.right != null) {if (node.val + 1 == node.right.val) {max = Math.max(max, num + 1);helper(node.right, num + 1);} else {helper(node.right, 1);}}}}
这篇关于Binary Tree Longest Consecutive Sequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!