Golang刷題Leetcode 104. Maximum Depth of Binary Tree

題目:Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

找到二叉樹的最大深度

思路

遞歸獲得左右子樹的深度,返回兩個深度的最大值+1

code

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
l := maxDepth(root.Left)
r := maxDepth(root.Right)
return max(l, r) + 1
}
func max(x, y int) int {
if x > y {
return x
}
return y
}

更多內容請移步我的repo:https://github.com/anakin/golang-leetcode


分享到:


相關文章: