给定一棵二叉树,求其最长连续数字路径(指的是形如x , x + 1 , x + 2 , . . . , x + k x,x+1,x+2,...,x+kx,x+1,x+2,...,x+k的路径)的长度。路径可以由任一点出发,任一点结束。
public class ShowMeBug { public static class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val) { this.val = val; } } public static void main(String[] args) { TreeNode node1 = new TreeNode(4); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(5); TreeNode node4 = new TreeNode(1); TreeNode node5 = new TreeNode(3); node1.left = node2; node1.right = node3; node2.left = node4; node2.right = node5; ShowMeBug showMeBug = new ShowMeBug(); int max = showMeBug.getTreeMaxSerLength(node1); System.out.println(max); } public int getTreeMaxSerLength(TreeNode root) { dfs(root, 1); return maxLength; } int maxLength = 1; public void dfs(TreeNode root, int length) { if (root == null) { return; } if (root.left != null) { if (root.left.val - root.val == 1) { maxLength = Math.max(maxLength, length + 1); dfs(root.left, length + 1); } else { dfs(root.left, 1); } } if (root.right != null) { if (root.right.val - root.val == 1) { maxLength = Math.max(maxLength, length + 1); dfs(root.right, length + 1); } else { dfs(root.right, 1); } } } }
。。。
标签:Binary,right,TreeNode,val,sequence,Tree,root,public,left From: https://www.cnblogs.com/guoyu1/p/17971177