七叶笔记 » golang编程 » Golang刷题Leetcode 104. Maximum Depth of Binary Tree

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:

相关文章