Javatpoint Logo
Javatpoint Logo

Q. Program to find the smallest element in a Binary Tree.

Explanation

In this program, we will find out the smallest node in the given binary tree. We first define variable min that will hold root's data. Then, we traverse through left sub-tree to find the smallest node in left subtree. Compare it with min and store minimum of two in variable min. Then, we traverse through right subtree to find smallest node and compare it with min. At the end, min will have the smallest node.

Program to find the smallest element in a Binary Tree

Above diagram represents a binary tree. Initially, min will hold 4. Recursive through left subtree.

Recursive through right subtree.

Recurse in right subtree of 3

So, smallest node in above binary tree is 1.

Algorithm

  1. Define Node class which has three attributes namely: data, left and right. Here, left represents the left child of the node and right represents the right child of the node.
  2. When a node is created, data will pass to data attribute of node and both left and right will be set to null.
  3. Define another class which has an attribute root.
    1. Root represent root node of the tree and initialize it to null.
  1. smallestElement() will find out the smallest node in binary tree:
    1. It checks whether root is null, which means tree is empty.
    2. If tree is not empty, define a variable min that will store temp's data.
    3. Find out the minimum node in left subtree by calling smallestElement() recursively. Store that value in leftMin. Compare the value of min with leftMin and store the minimum of two to min.
    4. Find out the minimum node in right subtree by calling smallestElement() recursively. Store that value in rightMin. Compare the value of min with rightMin and store the maximum of two to min.
    5. At the end, min will hold the smallest node in the binary tree.

Solution

Python

Output:

Smallest element in the binary tree: 1

C

Output:

Smallest element in the binary tree: 1

JAVA

Output:

Smallest element in the binary tree: 1

C#

Output:

Smallest element in the binary tree: 1

PHP

Output:

Smallest element in the binary tree: 1

Next TopicPrograms List





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA