You are required to use recursion for this problem. Code for BST and private inn
ID: 3885172 • Letter: Y
Question
You are required to use recursion for this problem. Code for BST and private inner class BSRNode are provided.
Do not alter the code that is given. recursiveSum returns the sum of all data in the tree.
Recall that instance members of a private inner class are accessible by the outer class so access Node fields directly as you do not have getters nor setters/
The method must be recursice or call a recursive helper method. You may write private helper methods if you need them.
If the tree is empty, the sum should be 0. Complete the instance method using recursion.
public class BST {
private BSTNode root;
public int recursiveSum() {
// here
}
private class BSTNode {
private int data;
private BSTNode left;
private BSTNode right;
}
}
Explanation / Answer
public class BST {
private BSTNode root;
public int recursiveSum() {
// instance function recurcivesum is modified here
if(root==null) return 0;
if( (root.left==null) && (root.right==null)) return 0;
return root.data+recursiveSum(root.left)+recursiveSum(root.right);
}
private class BSTNode {
private int data;
private BSTNode left;
private BSTNode right;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.