您的位置:首页 > 其它

leetcode 543. Diameter of Binary Tree

2017-07-23 16:52 225 查看
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].

Note: The length of path between two nodes is represented by the number of edges between them.
有这几个例子看一下。
1、

1
/
2

这个返回1。

2、



这个返回3

3、



这个返回8.  (是 -9的左子树 加上 -9的右子树)

由此可以看出,我们需要比较每个结点的“左子树高度+右子树高度”,然后取最大的那个即是结果。我们可以使用高度(即层数,包括顶点的层数)来进行递归。

package leetcode;

public class Diameter_of_Binary_Tree_543 {

public int diameterOfBinaryTree(TreeNode root) {
int[] max=new int[1];
cengshu(root, max);
return max[0];
}

public int cengshu(TreeNode node,int[] max){//连带node自己的总共层数
if(node==null){
return 0;
}
int left=cengshu(node.left, max);
int right=cengshu(node.right, max);
if(left+right>max[0]){
max[0]=left+right;
}
return Math.max(left, right)+1;
}
}
使用max[]是因为数组参数传的是引用而不是值,因此max[]就相当于一个全局变量了,所有改变都改的同一个max。

大神也跟我过程一样!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: