Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions src/Traversal.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,84 @@
public class Traversal {
public static void main(String[] args) {
TreeNode root = new TreeNode(10);

root.left = new TreeNode(9);
root.right = new TreeNode(15);

root.left.left = new TreeNode(5);
root.left.right = new TreeNode(2);

root.right = new TreeNode(15);
root.right.left = new TreeNode(-3);
root.right.right = new TreeNode(5);

root.right.right.right = new TreeNode(22);

// preorder(root);

//print out the sum
// int result = sum(root);
// System.out.println(result);

//print out oddSum
int result = oddSum(root);
System.out.println(result);


}

//methode to calculate the sum of the node odd in the tree, this methode return value so it's an integer method return an int.
public static int oddSum(TreeNode node){
if(node == null){
return 0;
}
int total = 0;
if(node.data % 2 != 0){
total += node.data;

}
total += oddSum(node.left);
total += oddSum(node.right);

return total;
}


//ordering the nodes and print them up
public static void preorder(TreeNode current){ //void because we don't print anything
//if null: return
if(current == null) return; //current is the TreeNode.

//print data
System.out.println(current.data); //current.data is to print the data inside current.

//search left
preorder(current.left);

//search right
preorder(current.right);

}


//methode to calculate the oddSum of the node odd in the tree, this methode return value so it's an integer method return an int.
public static int sum(TreeNode node){
//if null == 0
//because the method return a value, we need to return something. here if null, return 0.
if (node == null) return 0;
//else myValue + sum of left subtree + sum of right subtree

//initialisation of total at root data
int total = node.data;

//add sum of left subtree to my total.
//we use the method that we are in RN, because it's a method that does the sum of the treeNode
total += sum(node.left);

//add sum of right subtree to my total.
total += sum(node.right);

//return total
return total;
}
}
8 changes: 7 additions & 1 deletion src/TreeNode.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;

public TreeNode(int data){
this.data = data;
}


}