LeetCode 543. 二叉树的直径
一、题目详情
原题链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例 :
给定二叉树:
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3]
或者 [5,2,1,3]
。
二、递归法
/**
* 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; //定义全局变量保存最大路径
public int diameterOfBinaryTree(TreeNode root) {
max = 0; //初始化最大路径为0
depth(root); //计算最大路径
return max;
}
public int depth(TreeNode root){
if(root == null){
return 0; //访问到空节点时无深度,返回0
}
int leftDepth = depth(root.left); //左儿子为根的子树的深度
int rightDepth = depth(root.right); //右儿子为根的子树的深度
max = Math.max(leftDepth + rightDepth, max); 将每个节点最大直径(左子树深度+右子树深度)当前最大值比较并取大者
return Math.max(leftDepth,rightDepth) + 1; //返回该节点为根的子树的深度,用于之后的递归操作
}
}