From dcada1d8e90c40596ec79ab4f4b97a328cde4545 Mon Sep 17 00:00:00 2001 From: ductnn Date: Tue, 27 Feb 2024 23:55:52 +0700 Subject: [PATCH] add sol --- .../diameterofBinaryTree.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 leetcode/543.DiameterofBinaryTree/diameterofBinaryTree.go diff --git a/leetcode/543.DiameterofBinaryTree/diameterofBinaryTree.go b/leetcode/543.DiameterofBinaryTree/diameterofBinaryTree.go new file mode 100644 index 0000000..7b00bab --- /dev/null +++ b/leetcode/543.DiameterofBinaryTree/diameterofBinaryTree.go @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/diameter-of-binary-tree + +package main + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func diameterOfBinaryTree(root *TreeNode) int { + ans := 0 + var dfs func(root *TreeNode) int + dfs = func(root *TreeNode) int { + if root == nil { + return 0 + } + left, right := dfs(root.Left), dfs(root.Right) + ans = max(ans, left+right) + return 1 + max(left, right) + } + dfs(root) + return ans +} + +func max(a, b int) int { + if a > b { + return a + } + return b +}