Binary Tree Longest Consequence
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 private int result = 1; 12 public int longestConsecutive(TreeNode root) { 13 if (root == null) { 14 return 0; 15 } 16 getLongest(root, Integer.MIN_VALUE, 0); 17 return result; 18 } 19 20 private void getLongest(TreeNode root, int target, int count) { 21 if (root == null) { 22 result = Math.max(result, count); 23 return; 24 } 25 26 if (root.val == target + 1) { 27 count++; 28 result = Math.max(result, count); 29 } else { 30 count = 1; 31 } 32 getLongest(root.left, root.val, count); 33 getLongest(root.right, root.val, count); 34 } 35 }
Maximum value get should be count increase. Otherwise, it already breaks the consequences.
转载于:https://wwwblogs/shuashuashua/p/5645615.html
Binary Tree Longest Consequence
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 private int result = 1; 12 public int longestConsecutive(TreeNode root) { 13 if (root == null) { 14 return 0; 15 } 16 getLongest(root, Integer.MIN_VALUE, 0); 17 return result; 18 } 19 20 private void getLongest(TreeNode root, int target, int count) { 21 if (root == null) { 22 result = Math.max(result, count); 23 return; 24 } 25 26 if (root.val == target + 1) { 27 count++; 28 result = Math.max(result, count); 29 } else { 30 count = 1; 31 } 32 getLongest(root.left, root.val, count); 33 getLongest(root.right, root.val, count); 34 } 35 }
Maximum value get should be count increase. Otherwise, it already breaks the consequences.
转载于:https://wwwblogs/shuashuashua/p/5645615.html