Find Maximum Depth of a Binary Tree

package org.wesome.dsalgo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Objects;

@Data
@NoArgsConstructor
@AllArgsConstructor
class Node {
    int data;
    Node left, right;

    public Node(int data) {
        this.data = data;
        left = right = null;
    }
}

@Data
public class BinarySearchTree {
    Node root;

    public int findMaximumDepth(Node node) {
        if (Objects.isNull(node)) {
            return 0;
        }
        /*  check for left and right child  */
        if (Objects.isNull(node.left) && Objects.isNull(node.right)) {
            return 1;
        }
        /*  check for right sub child   */
        if (Objects.isNull(node.right)) {
            return findMaximumDepth(node.left) + 1;
        }
        /*  check for left child    */
        if (Objects.isNull(node.left)) {
            return findMaximumDepth(node.right) + 1;
        }

        /*  both child is present, so find the maximum of both   */
        return Math.max(findMaximumDepth(node.left), findMaximumDepth(node.right)) + 1;
    }

    void insert(int data) {
        System.out.println("BinarySearchTree.insert data = " + data);
        root = insert(root, data);
    }

    Node insert(Node root, int data) {
        if (Objects.isNull(root)) {
            Node tempNode = new Node(data);
            return tempNode;
        }
        if (data > root.data) {
            root.right = insert(root.right, data);
        } else {
            root.left = insert(root.left, data);
        }
        return root;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class BinarySearchTreeTest {
    @Test
    void findMaximumDepth() {
        BinarySearchTree binarySearchTree = new BinarySearchTree();
        binarySearchTree.insert(4);
        binarySearchTree.insert(2);
        binarySearchTree.insert(1);
        binarySearchTree.insert(3);
        binarySearchTree.insert(6);
        binarySearchTree.insert(5);
        binarySearchTree.insert(7);
        binarySearchTree.insert(8);
        Assertions.assertEquals(4, binarySearchTree.findMaximumDepth(binarySearchTree.root));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on