Blogs Hub

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

Maximum Depth of Binary Tree - Tree - Easy - LeetCode

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)