Maximum Depth of Binary Tree - Tree - Easy - LeetCode
💻 coding

Maximum Depth of Binary Tree - Tree - Easy - LeetCode

1 min read 147 words
1 min read
ShareWhatsAppPost on X
  • 1The maximum depth of a binary tree is the longest path from the root to a leaf node.
  • 2A leaf node is defined as a node with no children.
  • 3The provided solution has a time complexity of O(n) and space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The maximum depth of a binary tree is the longest path from the root to a leaf node."

Maximum Depth of Binary Tree - Tree - Easy - LeetCode

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.

Note: A leaf is a node with no children.

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.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 public int MaxDepth(TreeNode root) {
 if(root == null){
 return 0;
 }
 int left = MaxDepth(root.left);
 int right = MaxDepth(root.right);
 return 1+ Math.Max(left,right);
 }
}

Time Complexity: O(n) in the worst case

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 6 October 2020 · 1 min read · 147 words

Part of AskGif Blog · coding

You might also like