| 26 | } |
| 27 | |
| 28 | public void traverse(TreeNode root, int n) { |
| 29 | // if the node is null, return from the function (specially to handle if root of |
| 30 | // tree is null) |
| 31 | if (root == null) |
| 32 | return; |
| 33 | // shift the previous units place digit to ten's place by multiplying it by 10 |
| 34 | // and add the current value of node |
| 35 | n = n * 10 + root.val; |
| 36 | // if the node does not have a left or right children is null, |
| 37 | // the current node is leaf node, so add the value to sum and return |
| 38 | if (root.left == null && root.right == null) { |
| 39 | sum += n; |
| 40 | return; |
| 41 | } |
| 42 | // recurse for left subtree |
| 43 | traverse(root.left, n); |
| 44 | // recurse for right subtree |
| 45 | traverse(root.right, n); |
| 46 | } |
| 47 | } |