跳至主要內容

543. Diameter of Binary Tree


543. Diameter of Binary Treeopen in new window

🟢   🔖  深度优先搜索 二叉树  🔗 LeetCodeopen in new window

题目

Given the root of a binary tree, return 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.

The length of a path between two nodes is represented by the number of edges between them.

Example 1:

Input: root = [1,2,3,4,5]

Output: 3

Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

Input: root = [1,2]

Output: 1

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -100 <= Node.val <= 100

题目大意

给你一棵二叉树的根节点,返回该树的 直径 。

二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root

两节点之间路径的 长度 由它们之间边数表示。

解题思路

所谓二叉树的直径,就是左右子树的最大深度之和,那么直接的想法是对每个节点计算左右子树的最大高度,得出每个节点的直径,从而得出最大的那个直径。

但是由于 maxDepth 也是递归函数,所以上述方式时间复杂度较高。

这题类似 第 366 题 寻找二叉树的叶子节点 ,需要灵活运用二叉树的后序遍历,在 maxDepth 的后序遍历位置顺便计算最大直径。

代码

/**
 * @param {TreeNode} root
 * @return {number}
 */
var diameterOfBinaryTree = function (root) {
	if (!root) return 0;
	let res = 0;
	const maxDepth = (root) => {
		if (!root) return 0;
		let left = maxDepth(root.left);
		let right = maxDepth(root.right);
		res = Math.max(res, left + right);
		return Math.max(left, right) + 1;
	};
	maxDepth(root);
	return res;
};

相关题目

相关题目
- [1522. N 叉树的直径](./1522.md)
- [2246. 相邻字符不同的最长路径](https://leetcode.com/problems/longest-path-with-different-adjacent-characters)