/** * Java * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
The algrithm above is based on how to sum value of all nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicintsumOfTrees(TreeNode root){ if(root == null){ return0; } /* //get all value of leaves. int sum = 0; if(root.left == null && root.right == null){ sum = root.val; } */ int sum = root.val; int left = sumOfTrees(root.left); int right = sumOfTrees(root.right); return sum + left + right;