mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «543. Diameter of Binary Tree»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
778bcb1a2f
commit
aabf7eda27
1 changed files with 29 additions and 0 deletions
29
go/diameter-of-binary-tree.go
Normal file
29
go/diameter-of-binary-tree.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package diameter_of_binary_tree
|
||||
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
|
||||
func diameterAndHeight(node *TreeNode) (int, int) {
|
||||
if node == nil {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
leftDiameter, leftHeight := diameterAndHeight(node.Left)
|
||||
rightDiameter, rightHeight := diameterAndHeight(node.Right)
|
||||
|
||||
diameter := max(leftHeight+rightHeight, max(leftDiameter, rightDiameter))
|
||||
height := 1 + max(leftHeight, rightHeight)
|
||||
|
||||
return diameter, height
|
||||
}
|
||||
|
||||
func diameterOfBinaryTree(root *TreeNode) int {
|
||||
diameter, _ := diameterAndHeight(root)
|
||||
return diameter
|
||||
}
|
Loading…
Reference in a new issue