063_二叉树的直径
知识点:DFS、二叉树
LeetCode第五百四十三题:https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/
语言:GoLang
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var maxDistance int
func diameterOfBinaryTree(root *TreeNode) int {
maxDistance = 0
dfs(root)
return maxDistance
}
// 获取树的深度
func dfs(root *TreeNode) int {
if root == nil {
return 0
}
leftMax := dfs(root.Left)
rightMax := dfs(root.Right)
maxDistance = max(leftMax + rightMax, maxDistance)
return max(leftMax, rightMax) + 1
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}