Saturday, 22 January 2022

Height , Size , Maximum and Minimum of Binary Tree

 Height of Binary Tree:


Height of Binary Tree can be calculated by recursive call of left and right nodes 

static int height(Node root) {
        if (root == null) {
            return 0;
        }
        return Math.max(height(root.left), height(root.right)) + 1;
    }

Recursive stack of height function


Size of Binary Tree:

 static int size(Node root) {
        if (root == null) {
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }

Minimum of Binary Tree:
static int minimum(Node root) {
        if (root == null) {
            return Integer.MAX_VALUE;
        }
        return Math.min(root.data, Math.min(minimum(root.left), minimum(root.right)));
    }

Maximum of Binary Tree:

static int maximum(Node root) {
        if (root == null) {
            return Integer.MIN_VALUE;
        }
        return Math.max(root.data, Math.max(maximum(root.left), maximum(root.right)));
    }


Reference Video: 
Anuj Bhaiya(Hindi) : https://www.youtube.com/watch?v=hyAqgckHUiA&list=PLUcsbZa0qzu3yNzzAxgvSgRobdUUJvz7p


No comments:

Post a Comment