题目链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/
题目:
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.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
思路:
1、参考Binary Tree Paths 中保存所有从根到叶路径的方法,对所有路径处理一下再相加就能得到结果。这种方法是思路简单,利用 可以保存从根到叶所有路径的方法可以解决很多类似的root-leaf问题。不过需要O(n)的空间保存所有路径。
2、在递归过程中处理路径和。优点是算法简洁,不需要保存路径,空间复杂度O(1)。
算法1:
List<String> strList = new ArrayList<String>();
public int sumNumbers(TreeNode root) {
int sum = 0;
if (root != null) {
findPath(root, String.valueOf(root.val));
for (int i = 0; i < strList.size(); i++) {
sum += getConbinaFromStr(strList.get(i));
}
}
return sum;
}
public void findPath(TreeNode p, String path) {
if (p.left == null && p.right == null) {
strList.add(path);
}
if (p.left != null)
findPath(p.left, path + "->" + p.left.val);
if (p.right != null)
findPath(p.right, path + "->" + p.right.val);
}
public int getConbinaFromStr(String str) {
int sum = 0;
String s[] = str.split("->");
for (int i = 0; i < s.length; i++) {
int tmp = Integer.parseInt(s[i]);
sum = sum * 10 + tmp;
}
return sum;
}
算法2:
int sum = 0;
public int sumNumbers2(TreeNode root) {
addPSum(root, 0);
return sum;
}
public void addPSum(TreeNode root, int curNum) {
if (root == null)
return;
curNum = curNum * 10 + root.val; // 此时该路径的和
if (root.left == null && root.right == null) { // 从根走到叶了
sum += curNum;
return;
}
if (root.left != null) {
addPSum(root.left, curNum);
}
if (root.right != null) {
addPSum(root.right, curNum);
}
}