File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ class Node
3
+ {
4
+ int data ;
5
+ Node left ;
6
+ Node right ;
7
+ Node (int data )
8
+ {
9
+ this .data =data ;
10
+ left =right =null ;
11
+ }
12
+ }
13
+
14
+ class BinaryTree {
15
+ Node root ;
16
+ BinaryTree ()
17
+ {
18
+ root = null ;
19
+ }
20
+ BinaryTree (int data )
21
+ {
22
+ this .root =new Node (data );
23
+ }
24
+
25
+ int sumBT (Node head )
26
+ {
27
+
28
+ if (head ==null )
29
+ {
30
+ return 0 ;
31
+ }
32
+ return head .data + sumBT (head .left )+sumBT (head .right );
33
+ }
34
+
35
+ //method 2
36
+ static int sum =0 ;
37
+ public int sumBT1 (Node root )
38
+ {
39
+ sum =0 ;
40
+ return sum (root );
41
+ }
42
+ public int sum (Node root ){
43
+ if (root == null )
44
+ return 0 ;
45
+ sum (root .left );
46
+ sum (root .right );
47
+ sum += root .data ;
48
+ return sum ;
49
+ }
50
+ }
51
+
52
+ class treeSum {
53
+ public static void main (String [] args ) {
54
+
55
+ BinaryTree bt =new BinaryTree (2 );
56
+ bt .root .left =new Node (3 );
57
+ bt .root .right =new Node (5 );
58
+ bt .root .left .right =new Node (9 );
59
+ bt .root .right .left =new Node (7 );
60
+ System .out .println (bt .sumBT (bt .root ));
61
+ System .out .println (bt .sumBT1 (bt .root ));
62
+
63
+ //2nd binary tree
64
+ BinaryTree bt1 =new BinaryTree (2 );
65
+ bt1 .root .left =new Node (3 );
66
+ bt1 .root .right =new Node (10 );
67
+ bt1 .root .left .right =new Node (9 );
68
+ bt1 .root .right .left =new Node (6 );
69
+ System .out .println (bt1 .sumBT (bt1 .root ));
70
+ System .out .println (bt1 .sumBT1 (bt1 .root ));
71
+
72
+ }
73
+ }
You can’t perform that action at this time.
0 commit comments