I was trying to sum the value of BST's nodes with exactly one child. however, for some reason, it didn't going through. For example, the input{1,2,3,4,5,6,7,8,9,10} and the output of it should be 45. I only got 2. and for {5, 2, 1, 7, 6, 8, 10}, i got 0. I'm in the BST tree. Could anyone explain it and fix my code?
public class Node {
Integer value;
Node parent;
Node left;
Node right;
public Node(Integer value) {
this.value = value;
this.parent = null;
this.left = null;
this.right = null;
}
}
public Integer oddNodeSum() {
return oddNodeSum(root) ;
}
private Integer oddNodeSum(Node root) {
// START YOUR CODE
int index=0;
if (root==null){
return index+=0;
}
else {
if (root.left!=null&&root.right==null){
index += root.left.value;
oddNodeSum(root.left);
}
if (root.left==null&&root.right!=null){
index += root.right.value;
oddNodeSum(root.right);
}
return index;
}
}
the problem on your code is you are traversing node only when the condition of adding node (with one child) are satisfying. instead of it, you need to traverse all the child and you need to consider those node whose having only one child
.
i modified your code like following:
private int oddNodeSum(Node root) {
int sum = 0;
if(root == null) {
return 0;
}
/* node with only one child */
if((root.left == null && root.right != null) || (root.left != null && root.right == null)){
sum += root.val;
}
/* traverse all node and add whose having only one child */
sum += oddNodeSum(root.left);
sum += oddNodeSum(root.right);
return sum;
}