给的多叉树, 找这颗树里面最长的路径长度
解法就是在子树里面找最大的两个(或一个,如果只有一个子树的话)高度加起来。
对于每一个treenode, 维护它的最高的高度和第二高的高度,经过该点的最大路径就是: 最高高度+第二高高度,然后return 最高高度
1 package fbPractise; 2 3 import java.util.*; 4 5 class TreeNode { 6 int val; 7 List<TreeNode> children; 8 public TreeNode(int value) { 9 this.val = value; 10 this.children = new ArrayList<TreeNode>(); 11 } 12 } 13 14 15 public class LongestPathInTree { 16 static int maxLen = 0; 17 18 public static int findLongestPath(TreeNode node) { 19 findMaxPath(node); 20 return maxLen; 21 } 22 23 public static int findMaxPath(TreeNode node) { 24 if (node == null) return 0; 25 int heightest1 = 0; 26 int heightest2 = 0; 27 28 for (TreeNode child : node.children) { 29 int childHeight = findMaxPath(child); 30 31 if (childHeight > heightest1) { 32 heightest2 = heightest1; 33 heightest1 = childHeight; 34 } 35 else if (childHeight > heightest2) { 36 heightest2 = childHeight; 37 } 38 } 39 maxLen = Math.max(maxLen, 1 + heightest1 + heightest2); 40 return 1 + heightest1; 41 } 42 43 44 public static void main(String[] args) { 45 TreeNode node1 = new TreeNode(1); 46 TreeNode node2 = new TreeNode(2); 47 TreeNode node3 = new TreeNode(3); 48 TreeNode node4 = new TreeNode(4); 49 TreeNode node5 = new TreeNode(5); 50 TreeNode node6 = new TreeNode(6); 51 node1.children.add(node2); 52 node1.children.add(node3); 53 node2.children.add(node4); 54 node2.children.add(node5); 55 node5.children.add(node6); 56 57 int res = findLongestPath(node1); 58 System.out.println(res); 59 } 60 61 62 }