Home Summing binary tree producing unexpected results
Reply: 0

Summing binary tree producing unexpected results

user585
1#
user585 Published in July 21, 2018, 9:55 am

Trying to sum all nodes in a BST of Integers

The method is passed 0, but when it transitions from the left sub tree to right sub tree, the sum seems to decrease. Any help would be appreciated

The method is passed the root and a counter initialized to 0

public static int sumTree(TreeNode root,int sum) {
if (root != null) {
  System.out.println("current value: " + root.getValue());
  sum += (Integer) root.getValue();
  System.out.println(sum);
  sumTree(root.getLeft(),sum);
  sumTree(root.getRight(),sum);
}

return sum;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312379 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO