Skip to content

Instantly share code, notes, and snippets.

@viveknarang
Created February 10, 2019 23:18
Show Gist options
  • Save viveknarang/814db9413a5988dddc27625fca5ffc1c to your computer and use it in GitHub Desktop.
Save viveknarang/814db9413a5988dddc27625fca5ffc1c to your computer and use it in GitHub Desktop.
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers.
Question: https://leetcode.com/problems/sum-root-to-leaf-numbers/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> aList = new LinkedList<String>();
public int sumNumbers(TreeNode root) {
traverse(root, "");
int sum = 0;
for (String s : aList) {
sum += Integer.parseInt(s);
}
return sum;
}
public void traverse(TreeNode root, String n) {
if (root == null) {
return;
}
if (root != null) {
n += root.val;
}
if (root != null && root.left == null && root.right == null) {
if (n != "") {
aList.add(n);
}
return;
}
traverse(root.left, n);
traverse(root.right, n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment