Skip to content

Latest commit

 

History

History
50 lines (37 loc) · 962 Bytes

01-Maximum-Depth-of-Binary-Tree.md

File metadata and controls

50 lines (37 loc) · 962 Bytes

Maximum Depth of Binary Tree

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.

解法一:

传递level参数记录当前最大层数。题目给出的函数只有根节点参数,所以需要多写一个辅助函数。

funcmaxDepth(root*TreeNode) int { return_maxDepth(root, 0) } func_maxDepth(root*TreeNode, levelint) int { ifroot==nil { returnlevel } left:=_maxDepth(root.Left, level+1) right:=_maxDepth(root.Right, level+1) ifleft>right { returnleft } returnright }

解法二:

从叶子节点往回数。

funcmaxDepth(root*TreeNode) int { ifroot==nil { return0 } left:=maxDepth(root.Left) right:=maxDepth(root.Right) ifleft>right { returnleft+1 } returnright+1 }
close