只有一个节点的值总和 child

Sum of the value of node with only one child

我试图将 BST 节点的值与一个 child 相加。 但是,由于某种原因,它没有通过。 比如输入{1,2,3,4,5,6,7,8,9,10},输出应该是45,我只得到了2个。 对于 {5, 2, 1, 7, 6, 8, 10},我得到 0。我在 BST 树中。谁能解释一下并修复我的代码?

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;
        }

    }

oddNodeSum() 函数中初始化 index = 0 ,然后调用 oddNodeSum(root) 并将索引传递给 `oddNodeSum(root, index) 并尝试在那里实现逻辑.这将解决您的问题

你的代码的问题是只有当添加节点(有一个child)的条件满足时你才遍历节点。取而代之的是 you need to traverse all the child and you need to consider those node whose having only one child.

我修改了你的代码如下:

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;
}