fork download
  1. public class Main {
  2. public static class TreeNode {
  3. int val;
  4. TreeNode left;
  5. TreeNode right;
  6.  
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }
  11.  
  12. public static class BinaryTree {
  13. public int calculateSum(TreeNode root) {
  14. if (root == null) {
  15. return 0;
  16. }
  17.  
  18. int sum = root.val;
  19. sum += calculateSum(root.left);
  20. sum += calculateSum(root.right);
  21.  
  22. return sum;
  23. }
  24. }
  25.  
  26. public static void main(String[] args) {
  27. // Tworzenie drzewa
  28. TreeNode root = new TreeNode(2);
  29. root.left = new TreeNode(2);
  30. root.right = new TreeNode(5);
  31. root.left.left = new TreeNode(4);
  32. root.left.right = new TreeNode(9);
  33. root.right.left = new TreeNode(6);
  34. root.right.right = new TreeNode(2);
  35.  
  36. // Obliczanie sumy
  37. BinaryTree binaryTree = new BinaryTree();
  38. int sum = binaryTree.calculateSum(root);
  39. System.out.println("Suma wartości w drzewie: " + sum);
  40. }
  41. }
Success #stdin #stdout 0.12s 36708KB
stdin
Standard input is empty
stdout
Suma wartości w drzewie: 30