Blogs Hub

by Sumit Chourasia | Oct 06, 2020 | Category :coding | Tags : algorithm binary-tree data-structure easy leetcode tree

Minimum Depth of Binary Tree - Tree - Easy - LeetCode

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)

Contributed By: Sumit Chourasia
License Key Formatting - String - Easy - LeetCode
Contributed By: Sumit Chourasia
Reformat Department Table - Sql - Easy - LeetCode
Contributed By: Sumit Chourasia
Combination Sum II - Array - Medium - LeetCode