您如何让程序输出数字的总和而不是单独给出它们?
public class Tree {
private Node root;
public int sum;
public class Node{
private Node left;
private Node right;
private int val;
public Node(int data) {
this.val = data;
}
}
public void createTree() {
Node first = new Node(7);
Node second = new Node(2);
Node third = new Node(6);
Node fourth = new Node(4);
root = first;
first.left = second;
first.right = third;
second.left = fourth;
}
public void Sum(Node root) {
if(root == null) {
return;
}
System.out.print(root.val + " ");
Sum(root.left);
Sum(root.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree();
tree.Sum(tree.root);
}
}
当前输出是7 2 6 4但我希望它们在可能的情况下被添加到系统输出中的总和中。我不能因为某些原因让它工作,所以也许有人可以帮助我。
答案 0 :(得分:0)
您需要返回左右节点的总和,并从main()
打印返回值。此外,由于您传入sum()
,因此root
无需成为一种intance方法:
public static int sum(Node root) {
if(root == null) {
return 0;
}
return sum(root.left) + sum(root.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree();
System.out.println(sum(tree.root));
}
答案 1 :(得分:0)
您可以通过执行以下操作递归获取总和:
public double sum(Node root) {
double leftSum, rightSum, totalSum;
if (root == null) {
totalSum = 0;
return totalSum;
}else {
leftSum = sum(root.left);
rightSum = sum(root.right);
totalSum = root.val + leftSum + rightSum;
return totalSum;
}
}