@@ -74,6 +74,39 @@ public static void levelOrder(Node node) {
7474 }
7575 }
7676
77+ //Height of Tree
78+ public static int height (Node root ) {
79+ if (root == null ) {
80+ return 0 ;
81+ }
82+
83+ int leftHeight = height (root .getLeft ());
84+ int rightHeight = height (root .getRight ());
85+ return Math .max (leftHeight , rightHeight ) + 1 ;
86+ }
87+
88+ //Count of Nodes of Tree
89+ public static int countOfNodes (Node root ) {
90+ if (root == null ) {
91+ return 0 ;
92+ }
93+
94+ int leftNodes = countOfNodes (root .getLeft ());
95+ int rightNodes = countOfNodes (root .getRight ());
96+ return leftNodes + rightNodes + 1 ;
97+ }
98+
99+ //Sum of Nodes of Tree
100+ public static int sumOfNodes (Node root ) {
101+ if (root == null ) {
102+ return 0 ;
103+ }
104+
105+ int leftSum = sumOfNodes (root .getLeft ());
106+ int rightSum = sumOfNodes (root .getRight ());
107+ return leftSum + rightSum + root .getValue ();
108+ }
109+
77110
78111 public static void main (String [] args ) {
79112 BinarySearchTreeTraversal binarySearchTreeTraversal = new BinarySearchTreeTraversal ();
@@ -91,6 +124,10 @@ private static void buildTreeAndTraversalApproach2(BinarySearchTreeTraversal bin
91124 System .out .println (root .getValue ());
92125 binarySearchTreeTraversal .display (root );
93126 levelOrder (root );
127+
128+ System .out .println ("Height of Tree is " + height (root ));
129+ System .out .println ("Count of Nodes of Tree is " + countOfNodes (root ));
130+ System .out .println ("Sum of Nodes of Tree is " + sumOfNodes (root ));
94131 }
95132
96133 private static void buildTreeAndTraversalApproach1 (BinarySearchTreeTraversal binarySearchTreeTraversal ) {
0 commit comments