The Wayback Machine - https://web.archive.org/web/20240911091722/https://www.geeksforgeeks.org/diameter-of-a-binary-tree/
Open In App

Diameter of a Binary Tree

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
47.37%
2.9L

The diameter/width of a tree is defined as the number of nodes on the longest path between any two nodes. 

The diagram below shows two trees each with a diameter of nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). 

Naive Approach O(n^2)

  • The diameter of T’s left subtree.
  • The diameter of T’s right subtree.
  • The longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T)

Below is the implementation of the above approach

C++
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left, *right;
    Node(int value) {
        data = value;
        left = right = nullptr;
    }
};

// Function to compute the height of a tree.
int height(Node* node) {
  
    // Base case: tree is empty
    if (node == nullptr)
        return 0;

    // If tree is not empty then height = 1 +
    // max of left height and right heights
    return 1 + max(height(node->left), 
                   height(node->right));
}

// Function to get diameter of a binary tree
int diameter(Node* tree) {
  
    if (tree == nullptr)
        return 0;

    // Get the height of left and right sub-trees
    int lheight = height(tree->left);
    int rheight = height(tree->right);

    // Get the diameter of left and right sub-trees
    int ldiameter = diameter(tree->left);
    int rdiameter = diameter(tree->right);

    // Return max of the following three:
    // 1) Diameter of left subtree
    // 2) Diameter of right subtree
    // 3) Height of left subtree + height of right subtree + 1
    return max({lheight + rheight + 1, ldiameter, rdiameter});
}

// Driver Code
int main() {

    /* Constructed binary tree is
            1
           / \
          2   3
         / \
        4   5
    */
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    cout << diameter(root) << endl;

    return 0;
}
C
// Recursive optimized C program to find the diameter of a
// Binary Tree
#include <stdio.h>
#include <stdlib.h>

// A binary tree node has data, pointer to left child
// and a pointer to right child
struct node {
    int data;
    struct node *left, *right;
};

// function to create a new node of tree and returns pointer
struct node* newNode(int data);

// returns max of two integers
int max(int a, int b) { return (a > b) ? a : b; }

// function to Compute height of a tree.
int height(struct node* node);

// Function to get diameter of a binary tree
int diameter(struct node* tree)
{
    // base case where tree is empty
    if (tree == NULL)
        return 0;

    // get the height of left and right sub-trees
    int lheight = height(tree->left);
    int rheight = height(tree->right);

    // get the diameter of left and right sub-trees
    int ldiameter = diameter(tree->left);
    int rdiameter = diameter(tree->right);

    // Return max of following three
    // 1) Diameter of left subtree
    // 2) Diameter of right subtree
    // 3) Height of left subtree + height of right subtree +
    // 1

    return max(lheight + rheight + 1,
               max(ldiameter, rdiameter));
}

// UTILITY FUNCTIONS TO TEST diameter() FUNCTION

//  The function Compute the "height" of a tree. Height is
//  the number f nodes along the longest path from the root
//   node down to the farthest leaf node.
int height(struct node* node)
{
    // base case tree is empty
    if (node == NULL)
        return 0;

    // If tree is not empty then height = 1 + max of left
    // height and right heights
    return 1 + max(height(node->left), height(node->right));
}

// Helper function that allocates a new node with the
// given data and NULL left and right pointers.
struct node* newNode(int data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return (node);
}

// Driver Code
int main()
{

    /* Constructed binary tree is
              1
            /   \
          2      3
        /  \
      4     5
    */
    struct node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);

    // Function Call
    printf("Diameter of the given binary tree is %d\n",
           diameter(root));

    return 0;
}
Java
// Recursive optimized Java program to find the diameter of
// a Binary Tree

// Class containing left and right child of current
// node and key value
class Node {
    int data;
    Node left, right;

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

// Class to print the Diameter
class BinaryTree {
    Node root;

    // Method to calculate the diameter and return it to
    // main
    int diameter(Node root)
    {
        // base case if tree is empty
        if (root == null)
            return 0;

        // get the height of left and right sub-trees
        int lheight = height(root.left);
        int rheight = height(root.right);

        // get the diameter of left and right sub-trees
        int ldiameter = diameter(root.left);
        int rdiameter = diameter(root.right);

        /* Return max of following three
          1) Diameter of left subtree
          2) Diameter of right subtree
          3) Height of left subtree + height of right
          subtree + 1
         */
        return Math.max(lheight + rheight + 1,
                        Math.max(ldiameter, rdiameter));
    }

    // A wrapper over diameter(Node root)
    int diameter() { return diameter(root); }

    // The function Compute the "height" of a tree. Height
    // is the number of nodes along the longest path from
    // the root node down to the farthest leaf node.
    static int height(Node node)
    {
        // base case tree is empty
        if (node == null)
            return 0;

        // If tree is not empty then height = 1 + max of
        //  left height and right heights
        return (1
                + Math.max(height(node.left),
                           height(node.right)));
    }

    // Driver Code
    public static void main(String args[])
    {
        // creating a binary tree and entering the nodes
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        // Function Call
        System.out.println(
            "The diameter of given binary tree is : "
            + tree.diameter());
    }
}
Python
# Python3 program to find the diameter of binary tree

# A binary tree node


class Node:

    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None


# The function Compute the "height" of a tree. Height is the
# number of nodes along the longest path from the root node
# down to the farthest leaf node.

def height(node):

    # Base Case : Tree is empty
    if node is None:
        return 0

    # If tree is not empty then height = 1 + max of left
    # height and right heights
    return 1 + max(height(node.left), height(node.right))

# Function to get the diameter of a binary tree


def diameter(root):

    # Base Case when tree is empty
    if root is None:
        return 0

    # Get the height of left and right sub-trees
    lheight = height(root.left)
    rheight = height(root.right)

    # Get the diameter of left and right sub-trees
    ldiameter = diameter(root.left)
    rdiameter = diameter(root.right)

    # Return max of the following tree:
    # 1) Diameter of left subtree
    # 2) Diameter of right subtree
    # 3) Height of left subtree + height of right subtree +1
    return max(lheight + rheight + 1, max(ldiameter, rdiameter))


# Driver Code
if __name__ == "__main__":
    """
    Constructed binary tree is 
                1
              /   \
            2      3
          /  \
        4     5
    """

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    # Function Call
    print(diameter(root))

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// Recursive optimized C# program to find the diameter of
// a Binary Tree

// Class containing left and right child of current
// node and key value
using System;

namespace Tree {
class Tree<T> {
    public Tree(T value) { this.value = value; }
    public T value
    {
        get;
        set;
    }
    public Tree<T> left
    {
        get;
        set;
    }
    public Tree<T> right
    {
        get;
        set;
    }
}

public class TreeDiameter {
    Tree<int> root;

    // The function Compute the "height" of a tree. Height
    // is the number of nodes along the longest path from
    // the root node down to the farthest leaf node.
    int Height(Tree<int> node)
    {
        if (node == null)
            return 0;
        return 1
            + Math.Max(Height(node.left),
                       Height(node.right));
    }
    int Diameter(Tree<int> root)
    {
        if (root == null)
            return 0;

        // get the height of left and right sub-trees
        int lHeight = Height(root.left);
        int rHeight = Height(root.right);

        // get the diameter of left and right sub-trees
        int lDiameter = Diameter(root.left);
        int rDiameter = Diameter(root.right);

        //  Return max of following three
        // 1) Diameter of left subtree
        // 2) Diameter of right subtree
        // 3) Height of left subtree + height of right
        // subtree + 1
        return Math.Max(lHeight + rHeight + 1,
                        Math.Max(lDiameter, rDiameter));
    }

    // A wrapper over diameter(Node root)
    int Diameter() { return Diameter(root); }

    // Driver Code
    public static void Main(string[] args)
    {

        // creating a binary tree and entering the nodes
        TreeDiameter tree = new TreeDiameter();
        tree.root = new Tree<int>(1);
        tree.root.left = new Tree<int>(2);
        tree.root.right = new Tree<int>(3);
        tree.root.left.left = new Tree<int>(4);
        tree.root.left.right = new Tree<int>(5);

        Console.WriteLine(
            "The diameter of given binary tree is : "
            + tree.Diameter());
    }
}
}

// This code is contributed by krishaccot
JavaScript
<script>
// JavaScript program to find the diameter of binary tree
 
// A binary tree node
class Node{
   
  // Constructor to create a new node
  constructor(data){
    this.data = data
    this.left = null
    this.right = null 
  }

} 
 
// The function Compute the "height" of a tree. Height is the
// number of nodes along the longest path from the root node
// down to the farthest leaf node.
function height(node)
{

    // Base Case : Tree is empty
    if(node == null)
        return 0
 
    // If tree is not empty then height = 1 + max of left
    // height and right heights
    return 1 + Math.max(height(node.left), height(node.right))
}
 
// Function to get the diameter of a binary tree
function diameter(root){
 
    // Base Case when tree is empty
    if(root == null)
        return 0
 
    // Get the height of left and right sub-trees
    let lheight = height(root.left)
    let rheight = height(root.right)
 
    // Get the diameter of left and right sub-trees
    let ldiameter = diameter(root.left)
    let rdiameter = diameter(root.right)
 
    // Return max of the following tree:
    // 1) Diameter of left subtree
    // 2) Diameter of right subtree
    // 3) Height of left subtree + height of right subtree +1
    return Math.max(lheight + rheight + 1, Math.max(ldiameter, rdiameter))

}
 
 
// Driver Code

// Constructed binary tree is
//             1
//           /   \
//         2      3
//       /  \
//     4     5
 
root = new Node(1)
root.left = new Node(2)
root.right = new Node(3)
root.left.left = new Node(4)
root.left.right = new Node(5)
 
// Function Call
document.write("Diameter of the given binary tree is "+diameter(root))
 
// This code is contributed by shinjanpatra
</script>

Output
4

Time Complexity: O(N2)
Auxiliary Space: O(N) for call stack 

Efficient Approach O(n)

 The above implementation can be optimized by calculating the height in the same recursion rather than calling a height() separately.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left, *right;
    Node(int value) {
        data = value;
        left = nullptr;
        right = nullptr;
    }
};

int diameterOpt(Node* root, int* height) {
  
    // lh --> Height of left subtree
    // rh --> Height of right subtree
    int lh = 0, rh = 0;

    // ldiameter  --> diameter of left subtree
    // rdiameter  --> Diameter of right subtree
    int ldiameter = 0, rdiameter = 0;

    if (root == nullptr) {
        *height = 0;
        return 0; // diameter is also 0
    }

    // Get the heights of left and right subtrees in lh and
    // rh and store the returned values in ldiameter and
    // rdiameter
    ldiameter = diameterOpt(root->left, &lh);
    rdiameter = diameterOpt(root->right, &rh);

    // Height of current node is max of heights of left and
    // right subtrees plus 1
    *height = max(lh, rh) + 1;

    return max({lh + rh + 1, ldiameter, rdiameter});
}

// Driver Code
int main() {

    /* Constructed binary tree is
            1
           / \
          2   3
         / \
        4   5
    */
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);

    int height = 0;
  
    cout << diameterOpt(root, &height) << endl;

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// A binary tree node has data, pointer to left child
// and a pointer to right child
struct Node {
    int data;
    struct Node *left, *right;
};

// Function to return the maximum of two integers
int max(int a, int b) {
    return (a > b) ? a : b;
}

// Function to calculate the diameter of the tree
int diameterOpt(struct Node* root, int* height) {
    int lh = 0, rh = 0;
    int ldiameter = 0, rdiameter = 0;

    if (root == NULL) {
        *height = 0;
        return 0;  // diameter is also 0
    }

    ldiameter = diameterOpt(root->left, &lh);
    rdiameter = diameterOpt(root->right, &rh);

    *height = max(lh, rh) + 1;

    return max(lh + rh + 1, max(ldiameter, rdiameter));
}

struct Node* createNode(int value) {
    struct Node* node =
      (struct Node*)malloc(sizeof(struct Node));
    node->data = value;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Driver Code
int main() {
    /* Constructed binary tree is
            1
           / \
          2   3
         / \
        4   5
    */
    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);

    int height = 0;

    // Function Call
    printf("%d", diameterOpt(root, &height));

    return 0;
}
Java
// Recursive Java program to find the diameter of a
// Binary Tree

// Class containing left and right child of current
// node and key value
class Node {
    int data;
    Node left, right;

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

// A utility class to pass height object
class Height {
    int h;
}

// Class to print the Diameter
class BinaryTree {
    Node root;

    // define height =0 globally and  call
    // diameterOpt(root,height) from main
    int diameterOpt(Node root, Height height)
    {
        // lh --> Height of left subtree
        // rh --> Height of right subtree
        Height lh = new Height(), rh = new Height();

        if (root == null) {
            height.h = 0;
            return 0; // diameter is also 0
        }
        /*
                ldiameter  --> diameter of left subtree
                rdiameter  --> Diameter of right subtree
                Get the heights of left and right subtrees
           in lh and rh. And store the returned values in
           ldiameter and ldiameter*/
        int ldiameter = diameterOpt(root.left, lh);
        int rdiameter = diameterOpt(root.right, rh);

        // Height of current node is max of heights of left
        // and right subtrees plus 1
        height.h = Math.max(lh.h, rh.h) + 1;

        return Math.max(lh.h + rh.h + 1,
                        Math.max(ldiameter, rdiameter));
    }

    // A wrapper over diameter(Node root)
    int diameter()
    {
        Height height = new Height();
        return diameterOpt(root, height);
    }

    // The function Compute the "height" of a tree. Height
    // is
    //  the number f nodes along the longest path from the
    //  root node down to the farthest leaf node.
    static int height(Node node)
    {
        // base case tree is empty
        if (node == null)
            return 0;

        // If tree is not empty then height = 1 + max of
        // left height and right heights
        return (1
                + Math.max(height(node.left),
                           height(node.right)));
    }

    // Driver Code
    public static void main(String args[])
    {
        // creating a binary tree and entering the nodes
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        // Function Call
        System.out.println(
            "The diameter of given binary tree is : "
            + tree.diameter());
    }
}
Python
# Python3 program to find the diameter of a binary tree
# A binary tree Node


class Node:

    # Constructor to create a new Node
    def __init__(self, data):
        self.data = data
        self.left = self.right = None

# utility class to pass height object


class Height:
    def __init(self):
        self.h = 0

# Optimised recursive function to find diameter
# of binary tree


def diameterOpt(root, height):

    # to store height of left and right subtree
    lh = Height()
    rh = Height()

    # base condition- when binary tree is empty
    if root is None:
        height.h = 0
        return 0

    # ldiameter --> diameter of left subtree
    # rdiameter  --> diameter of right subtree

    # height of left subtree and right subtree is obtained from lh and rh
    # and returned value of function is stored in ldiameter and rdiameter

    ldiameter = diameterOpt(root.left, lh)
    rdiameter = diameterOpt(root.right, rh)

    # height of tree will be max of left subtree
    # height and right subtree height plus1

    height.h = max(lh.h, rh.h) + 1

    # return maximum of the following
    # 1)left diameter
    # 2)right diameter
    # 3)left height + right height + 1
    return max(lh.h + rh.h + 1, max(ldiameter, rdiameter))

# function to calculate diameter of binary tree


def diameter(root):
    height = Height()
    return diameterOpt(root, height)


# Driver Code
if __name__ == "__main__":
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    """
  Constructed binary tree is 
              1
          /   \
          2      3
        /  \
      4     5
  """

    print("The diameter of the binary tree is:", end=" ")
    # Function Call
    print(diameter(root))

# This code is contributed by Shweta Singh(shweta44)
C#
// Recursive C# program to find the diameter of a
// Binary Tree
using System;
using System.Collections.Generic;

// Class containing left and right child of current
// node and key value
class Node {
    public int data;
    public Node left, right;

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

// A utility class to pass height object
class Height {
    public int h;
}

// Class to print the Diameter
class BinaryTree {
    public Node root;

    // define height =0 globally and  call
    // diameterOpt(root,height) from main
    public int diameterOpt(Node root, Height height)
    {
        // lh --> Height of left subtree
        // rh --> Height of right subtree
        Height lh = new Height(), rh = new Height();

        if (root == null) {
            height.h = 0;
            return 0; // diameter is also 0
        }

        // ldiameter  --> diameter of left subtree
        // rdiameter  --> Diameter of right subtree
        // Get the heights of left and right subtrees in lh
        /*and rh And store the returned values in ldiameter
                and ldiameter */
        int ldiameter = diameterOpt(root.left, lh);
        int rdiameter = diameterOpt(root.right, rh);

        // Height of current node is max of heights of left
        // and right subtrees plus 1
        height.h = Math.Max(lh.h, rh.h) + 1;

        return Math.Max(lh.h + rh.h + 1,
                        Math.Max(ldiameter, rdiameter));
    }

    // A wrapper over diameter(Node root)
    public int diameter()
    {
        Height height = new Height();
        return diameterOpt(root, height);
    }

    // The function Compute the "height" of a tree. Height
    // is
    //  the number f nodes along the longest path from the
    //  root node down to the farthest leaf node.
    public int height(Node node)
    {
        // base case tree is empty
        if (node == null)
            return 0;

        // If tree is not empty then height = 1 + max of
        // left height and right heights
        return (1
                + Math.Max(height(node.left),
                           height(node.right)));
    }

    // Driver Code
    static void Main()
    {

        // creating a binary tree and entering the nodes
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        // Function Call
        Console.Write(
            "The diameter of given binary tree is : "
            + tree.diameter());
    }
}

// This code is contributed by divyesh072019.
JavaScript
<script>
// JavaScript program to find the diameter of a binary tree
// A binary tree Node
class Node{

    // Constructor to create a new Node
    constructor(data){
        this.data = data
        this.left = this.right = null
    }
}

// utility class to pass height object
class Height
{
    constructor()
    {
        this.h = 0
    }
}

// Optimised recursive function to find diameter
// of binary tree
function diameterOpt(root, height){

    // to store height of left and right subtree
    let lh = new Height()
    let rh = new Height()

    // base condition- when binary tree is empty
    if(root == null)
    {
        height.h = 0
        return 0
    }

    
    // ldiameter --> diameter of left subtree
    // rdiameter  --> diameter of right subtree
    
    // height of left subtree and right subtree is obtained from lh and rh
    // and returned value of function is stored in ldiameter and rdiameter
    let ldiameter = diameterOpt(root.left, lh)
    let rdiameter = diameterOpt(root.right, rh)

    // height of tree will be max of left subtree
    // height and right subtree height plus1
    height.h = Math.max(lh.h, rh.h) + 1

    // return maximum of the following
    // 1)left diameter
    // 2)right diameter
    // 3)left height + right height + 1
    return Math.max(lh.h + rh.h + 1, Math.max(ldiameter, rdiameter))
}

// function to calculate diameter of binary tree
function diameter(root){
    let height = new Height()
    return diameterOpt(root, height)
}


// Driver Code 
let root = new Node(1)
root.left = new Node(2)
root.right = new Node(3)
root.left.left = new Node(4)
root.left.right = new Node(5)


// Constructed binary tree is 
//             1
//           /   \
//         2      3
//       /  \
//     4     5


// Function Call
document.write(diameter(root))

// This code is contributed by Shinjanpatra

</script>

Output
4

Time Complexity: O(N) 
Auxiliary Space: O(N) due to recursive calls.

Related Article:
Diameter of an N-ary tree



Previous Article
Next Article

Similar Reads

Diameter of a Binary Indexed Tree with N nodes
Given a Binary Indexed Tree with N nodes except root node 0 (Numbered from 1 to N), Find its diameter. Binary Indexed Tree is a tree where parent of a node number X = X - (X &amp; (X - 1)) i.e. last bit is unset in X. The diameter of a tree is the longest simple path between any two leaves. Examples: Input: N = 12 Output: 6 Explanation: Path from n
7 min read
Finding the lexicographically smallest diameter in a binary tree
Given a binary tree where node values are lowercase alphabets, the task is to find the lexicographically smallest diameter. Diameter is the longest path between any two leaf nodes, hence, there can be multiple diameters in a Binary Tree. The task is to print the lexicographically smallest diameter among all possible diameters.Examples: Input: a / \
13 min read
Diameter of a Binary Tree in O(n) [A new method]
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are colored (note that there may be more than one path in the tree of the same diameter).  Examples:  Input : 1 / \ 2 3 / \ 4 5Output : 4Input
6 min read
Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Possible edges of a tree for given diameter, height and vertices
Find a tree with the given values and print the edges of the tree. Print "-1", if the tree is not possible. Given three integers n, d and h. n -&gt; Number of vertices. [1, n] d -&gt; Diameter of the tree (largest distance between two vertices). h -&gt; Height of the tree (longest distance between vertex 1 and another vertex) Examples : Input : n =
8 min read
DP on Trees | Set-3 ( Diameter of N-ary Tree )
Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree). Example 1: Example 2: Different approaches to solving these problems have already been discussed: https://www.geeksforgeeks.org/diameter-n-ary-tree/https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/ In
9 min read
Make a tree with n vertices , d diameter and at most vertex degree k
Given three integers N, D and K. The task is to check whether it is possible to make a tree with exactly N vertices, D diameter (the number of edges in the longest path between any two vertices), and degree of each vertex must be at most K. If it is possible then print all the possible edges otherwise print No. Examples: Input: N = 6, D = 3, K = 4
11 min read
Diameter of a tree using DFS
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with a diameter of five, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length five, but no path longer than five n
8 min read
CSES Solutions - Tree Diameter
You are given a tree consisting of n nodes. The diameter of a tree is the maximum distance between two nodes. Your task is to determine the diameter of the tree. Examples: Input: n = 5, edges = { { 1, 2 }, { 1, 3 }, { 3, 4 }, { 3, 5 } };Output: 3 Input: n = 4, edges = { { 1, 2 }, { 1, 3 }, { 3, 4 }};Output: 3 Approach: We can uses a Depth-First Sea
6 min read
Diameter of an N-ary tree
The diameter of an N-ary tree is the longest path present between any two nodes of the tree. These two nodes must be two leaf nodes. The following examples have the longest path[diameter] shaded. Example 1: Example 2:  Prerequisite: Diameter of a binary tree. The path can either start from one of the nodes and go up to one of the LCAs of these node
15+ min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Find the center of the circle using endpoints of diameter
Given two endpoint of diameter of a circle (x1, y1) and (x2, y2) find out the center of a circle. Examples : Input : x1 = -9, y1 = 3, and x2 = 5, y2 = –7 Output : -2, –2 Input : x1 = 5, y1 = 3 and x2 = –10 y2 = 4 Output : –2.5, 3.5 Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is : M = ((x 1 + x 2) / 2, (y 1 + y 2) / 2) The ce
4 min read
Find minimum Diameter BST having Sum equal to target K
Given a binary tree and a target K, the task is to find the diameter of the minimum subtree having sum equal to K which is also a binary search tree. Return -1 if not possible. Examples: Input: K = 38 13 / \ 5 23 / \ / \ N 17 N N / \ 16 NOutput: 3Explanation: 5, 17, 16 is the smallest subtree with diameter 3. Input: K = 73 7 / \ N 23 / \ 10 23 / \
11 min read
Find the other-end coordinates of diameter in a circle
Given Centre coordinate (c1, c2) and one coordinate (x1, y1) of the diameter of a circle, find the other end coordinate point (x2, y2) of diameter. Examples: Input : x1 = –1, y1 = 2, and c1 = 3, c2 = –6 Output : x2 = 7, y2 = -14 Input : x1 = 6.4, y1 = 3 and c1 = –10.7, c2 = 4 Output : x2 = -27.8, y2 = 5 The Midpoint Formula: The midpoint of two end
5 min read
Program to find the diameter, cycles and edges of a Wheel Graph
Wheel Graph: A Wheel graph is a graph formed by connecting a single universal vertex to all vertices of a cycle. Properties: Wheel graphs are Planar graphs.There is always a Hamiltonian cycle in the Wheel graph.Chromatic Number is 3 and 4, if n is odd and even respectively. Problem Statement: Given the Number of Vertices in a Wheel Graph. The task
7 min read
Find the Diameter or Longest chord of a Circle
Given a circle with radius 'r' is given, the task is to find the diameter or longest chord of the circle.Examples: Input: r = 4 Output: 8 Input: r = 9 Output: 18 Proof that the Longest chord of a circle is its Diameter: Draw circle O and any chord AB on it.From one endpoint of the chord, say A, draw a line segment through the centre. That is, draw
4 min read
Length of the chord the circle if length of the another chord which is equally inclined through the diameter is given
Given are two chords which are equally inclined through the diameter of the circle. Length of one chord is given. The task is to find the length of another chord.Examples: Input: z = 48 Output: 48 degrees Input: z = 93 Output: 93 degrees Approach: Let AB and AC be the two chords of the circle having the center at O.now, in the figure we see, OL is
3 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read