LeetCode-543. Diameter of Binary Tree (Java)

来源:互联网 发布:淘宝退款了货收到了 编辑:程序博客网 时间:2024/06/02 03:15

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].

----------------------------------------------------------------------------------------------------------------------------------------------------------
题意
求二叉树两个节点之间最长的路径。
思路
递归求解,每次返回左右子树最大长度,然后将两个最大的子树长度相加,得到二叉树节点之间最长路径。
代码
public static int diameterOfBinaryTree(TreeNode root) {if(root == null){return 0;}else{    int left = diameterOfBinaryTree(root.left);    int right = diameterOfBinaryTree(root.right);    //两个左右子树的最大深度相加    max = Math.max(max, left+right);        //返回该节点最大的深度    return 1+Math.max(left, right);}}




原创粉丝点击