Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Example 1:
Input: root = {3,9,20,null,null,15,7}
Output: 3



Approach

Java


public class MaxmumDepthBinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(maxDepth(root));
    }

    static int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        if (root.left == null && root.right == null)
            return 1;
        if (root.left == null)
            return 1 + maxDepth(root.right);
        if (root.right == null)
            return 1 + maxDepth(root.left);

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data=data;
        this->left=NULL;
        this->right=NULL;
    }
};


int maxDepth(TreeNode* root
{
        if(root==NULL)
              return 0;
        if(root->left==NULL &&root->right==NULL)
               return 1;
        if(root->left==NULL)
               return 1+maxDepth(root->right);
        if(root->right==NULL)
               return 1+maxDepth(root->left);
        return max(maxDepth(root->left),maxDepth(root->right))+1;
}

int main()
{
    TreeNode *root=new TreeNode(3);
    root->left=new TreeNode(9);
    root->right=new TreeNode(20);
    root->right->left=new TreeNode(15);
    root->right->right=new TreeNode(7);
    cout<<maxDepth(root);
    return 0;
}


No comments:

Post a Comment