给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
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.
示例 : 给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
解题思路 此过程采用后序遍历
假设我们知道对于该节点的左儿子向下遍历经过最多的节点数 L (即以左儿子为根的子树的深度) 和其右儿子向下遍历经过最多的节点数 R (即以右儿子为根的子树的深度),那么以该节点为起点的路径经过节点数的最大值即为 L+R+1 。
var diameterOfBinaryTree = function(root) {
let answer=1
var dfs=function(root){
if(!root){
return 0
}
let l=dfs(root.left)
let r=dfs(root.right)
answer=Math.max(answer,l+r+1)
return Math.max(l,r)+1
}
dfs(root)
return answer-1
};
var diameterOfBinaryTree = function(root) {
let answer=0
var dfs=function(root){
if(!root){
return 0
}
let l=dfs(root.left)
let r=dfs(root.right)
answer=Math.max(answer,l+r)
return Math.max(l,r)+1
}
dfs(root)
return answer
};
leetcode:https://leetcode-cn.com/problems/diameter-of-binary-tree/
|