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

Minimum Depth of Binary Tree - Tree - Easy - LeetCode

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

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The minimum depth of a binary tree is the shortest path from the root to the nearest leaf node."

Minimum Depth of Binary Tree - Tree - Easy - LeetCode

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest 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 minimum depth = 2.

/**
 * 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 MinDepth(TreeNode root) {
 if(root == null){
 return 0;
 }
 if(root.left == null && root.right == null){
 return 1;
 }
 int left = int.MaxValue;
 int right = int.MaxValue;
 if(root.left != null){
 left = MinDepth(root.left);
 } 
 
 if(root.right != null){
 right = MinDepth(root.right); 
 }
 
 return 1+ Math.Min(left, right);
 }
}

Time Complexity: O(n)

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 · 169 words

Part of AskGif Blog · coding

You might also like