Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
题目
给定一棵二叉树,求任意两个节点的最长路径长度。
思路
长度的定义是边的个数,不是node的个数
跟 [leetcode]124. Binary Tree Maximum Path Sum二叉树最大路径和 思路一致。
代码
1 class Solution { 2 public int diameterOfBinaryTree(TreeNode root) { 3 /* 要么用个global variable放在class下,要么用长度为1的一维数组来存。 4 这里因为求edge的数量,初始化为一维数组的default值0是可行的。 5 */ 6 int[] diameter = new int[1]; 7 dfs(root, diameter); 8 return diameter[0]; 9 } 10 11 private int dfs(TreeNode node, int[] diameter) { 12 if(node == null){return 0;} 13 14 int lh = dfs(node.left, diameter); 15 int rh = dfs(node.right, diameter); 16 17 diameter[0] = Math.max(diameter[0], lh + rh); 18 return Math.max(lh, rh) + 1; 19 } 20 }