Advertisement
111. Minimum Depth of Binary Tree
EasyView on LeetCode
Time: O(n)
Space: O(h)
Approach
DFS recursion. A node with one null child is not a leaf, so recurse only on the non-null side in that case.
111.cs
C#
// Approach: DFS recursion. A node with one null child is not a leaf, so
// recurse only on the non-null side in that case.
// Time: O(n) Space: O(h)
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)
return MinDepth(root.right) + 1;
if (root.right == null)
return MinDepth(root.left) + 1;
return Math.Min(MinDepth(root.left), MinDepth(root.right)) + 1;
}
}Advertisement
Was this solution helpful?