LeetCode 104. 二叉树的最大深度(Golang)

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    i := 0
	j := 0
	if root == nil {
		return 0
	}
	i = maxDepth(root.Left) + 1
	j = maxDepth(root.Right) + 1
	if i < j {
		i, j = j, i
	}
	return i
}

猜你喜欢

转载自blog.csdn.net/luckydog612/article/details/83020395