Class SizeOfBinaryTree

java.lang.Object
com.amritpandey23.dsalibrary.tree.SizeOfBinaryTree

public class SizeOfBinaryTree extends Object
Calculate total number of nodes i.e. size of a binary tree. The word "size" is quite ambiguous as it can be mean many things in context of a tree. It can very well mean the height or depth of the tree to a non-native english speaker. Here we mean total number of nodes in the tree by "size" which is a common term also used in the Java collections library.
  • Constructor Details

    • SizeOfBinaryTree

      public SizeOfBinaryTree()
  • Method Details

    • getSizeRecursively

      public static <T> Integer getSizeRecursively(TreeNode<T> node)
      Calculates the size of a binary tree recursively. This method traverses the tree in a depth-first manner, summing up nodes in each subtree.
      Type Parameters:
      T - the type of the values stored in the tree nodes
      Parameters:
      node - the root of the binary tree
      Returns:
      the total number of nodes in the tree
    • getSizeIteratively

      public static <T> Integer getSizeIteratively(TreeNode<T> node)
      Calculates the size of a binary tree iteratively. This method uses a breadth-first traversal (level-order) to count the nodes in the tree.
      Type Parameters:
      T - the type of the values stored in the tree nodes
      Parameters:
      node - the root of the binary tree
      Returns:
      the total number of nodes in the tree