MDGSF Software Engineer

[算法学习][leetcode] 104 Maximum Depth of Binary Tree

2017-11-16
mdgsf
Art

https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

题目

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

题目翻译

题目解析

参考答案

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

    iLeftDepth := maxDepth(root.Left)
    iRightDepth := maxDepth(root.Right)

    iMax := 0
    if iLeftDepth > iRightDepth {
        iMax = iLeftDepth
    } else {
        iMax = iRightDepth
    }

    return iMax + 1
}

weixingongzhonghao

Similar Posts

Comments