NOTE
Maximum Depth of Binary Tree
LeetCode notes on Maximum Depth of Binary Tree.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given a binary tree, find its maximum depth.
The depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.
2. Approach
- Approach 1
- Computing depth uses DFS
- The depth of the current node is 1 plus the larger depth of its left and right subtrees, which is postorder traversal
3. Implementation
/**
* 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
}
return 1 + max(maxDepth(root.Left), maxDepth(root.Right))
}
func max(a, b int) int {
if a>b {
return a
}
return b
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub