Recommended Posts

DSA (Easy) — Binary Tree — Maximum Depth of Binary Tree (Python, Typescript & Go)

0 comments

simplestack0.312 months agoPeakD4 min read


https://files.peakd.com/file/peakd-hive/simplestack/ALAEAtKtSso1VEHXaGJrk5yP6qffBgLfrqbSUxYXvTiuY1ZfUb8Nv36wxBNFVN2.png

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:


https://files.peakd.com/file/peakd-hive/simplestack/EoCpLyhto76L9nBvyF33ZiS7N2ok8WYT3ziKYTUfS8XZtkqHfem86zr7ayDVsKRPHUi.png

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

Explanation

function maxDepth(tree_root):
  if tree_root is nothing:
    return 0
  else:
    depth_of_left_subtree = maxDepth(tree_root's left child)
    depth_of_right_subtree = maxDepth(tree_root's right child)
    return the larger of (depth_of_left_subtree, depth_of_right_subtree) + 1

Imagine you’re trying to find how deep a tree is.

  1. Check if there’s anything there: If you’re looking at an empty spot (no tree), the depth is 0.
  2. Look at the branches: If there is a tree, look at its left branch and its right branch.
  3. Find the depth of each branch: Figure out how deep the left branch goes and how deep the right branch goes (by doing the same process for each of their branches).
  4. Take the deeper branch: The overall depth of the tree is the depth of the deeper of the two branches.
  5. Add one for the current level: Since you started at the root of the tree, you need to add 1 to the depth you found in step 4. This accounts for the current level you are on.

Essentially, you keep going down the tree, counting how many levels you can go on each side, and then you pick the side that goes the furthest down.

Implementations

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        """
        Calculates the maximum depth of a binary tree.

        Args:
            root: The root node of the binary tree.

        Returns:
            The maximum depth of the binary tree.
        """
        if root is None:
            return 0
        else:
            left_depth = self.maxDepth(root.left)
            right_depth = self.maxDepth(root.right)
            return max(left_depth, right_depth) + 1

Typescript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 * val: number
 * left: TreeNode | null
 * right: TreeNode | null
 * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 * this.val = (val===undefined ? 0 : val)
 * this.left = (left===undefined ? null : left)
 * this.right = (right===undefined ? null : right)
 * }
 * }
 */

function maxDepth(root: TreeNode | null): number {
    if (root === null) {
        return 0;
    } else {
        const leftDepth = maxDepth(root.left);
        const rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
};

Go

/**
 * 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
 }
 leftDepth := maxDepth(root.Left)
 rightDepth := maxDepth(root.Right)
 return max(leftDepth, rightDepth) + 1
}

func max(a, b int) int {
 if a > b {
  return a
 }
 return b
}

If you liked this article I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.

Muchas gracias!

Follow me for more content like this.

X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me

Down below you can find other ways to tip my work.

BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"

Comments

Sort byBest