diff --git a/src/Traversal.java b/src/Traversal.java index 8da0f79..73a3644 100644 --- a/src/Traversal.java +++ b/src/Traversal.java @@ -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; } } diff --git a/src/TreeNode.java b/src/TreeNode.java index acd9639..fc656a6 100644 --- a/src/TreeNode.java +++ b/src/TreeNode.java @@ -1,4 +1,10 @@ public class TreeNode { + public int data; + public TreeNode left; + public TreeNode right; + + public TreeNode(int data){ + this.data = data; + } - } \ No newline at end of file