题目来源:
leetcode题目,网址:543. 二叉树的直径 - 力扣(LeetCode)
解题思路:
遍历二叉树,计算以每个节点为根节点时的左子树深度和右子树深度之和,和的最大值即为二叉树的直径长度。
解题代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max=0;
public int diameterOfBinaryTree(TreeNode root) {
int[] res=new int[1];
forMax(root,res);
return res[0];
}
public static int forMax(TreeNode root,int[] res){
if(root==null)
return 0;
int left=forMax(root.left,res);
int right=forMax(root.right,res);
if(left+right > res[0] )
res[0]=left+right;
return Math.max(left,right)+1;
}
}
总结:
官方节点是通过设置全局变量获得最大值,而我是通过传递引用获得最大值。