【LeetCode】543. 二叉树的直径
算法现在就是大厂、外企的硬指标。开发、测开、测试,想往上总是绕不开的。
题目描述
难度:【简单】 标签:【二叉树】
给定一棵二叉树,你需要计算它的直径长度。
一棵二叉树的直径长度是任意两个结点路径长度中的最大值。
这条路径可能穿过也可能不穿过根结点。
题目地址:https://leetcode-cn.com/problems/diameter-of-binary-tree/description/
示例
给定二叉树
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 {
private int maxPath = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return maxPath;
}
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
// 更新最大直径
maxPath = Math.max(leftDepth + rightDepth, maxPath);
// 返回出当前这个节点的最大深度
return Math.max(leftDepth, rightDepth) + 1;
}
}