题目:
给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。
例如,从根到叶子节点路径 1->2->3 代表数字 123。
计算从根到叶子节点生成的所有数字之和。
输入: [1,2,3]
1
/ \
2 3
输出: 25
解释:
从根到叶子节点路径 1->2 代表数字 12.
从根到叶子节点路径 1->3 代表数字 13.
因此,数字总和 = 12 + 13 = 25.
解法:
这道题,题意就是遍历二叉树,先遍历根节点,再遍历左子节点,直到叶子节点(叶子节点没有子节点)。形成一个数字,然后遍历右子节点,直到叶子节点。
看看,这像什么?这其实就是二叉树的前序遍历的应用。
此处,应用了前序遍历+回溯算法。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// temp 用来装从根节点到叶子节点的数字
LinkedList<Integer> temp = new LinkedList<Integer>();
LinkedList<String> list = new LinkedList<String>();
public void dfsfun(TreeNode root){
if (root.left==null && root.right==null) {
temp.add(root.val);
// 拼接temp中的所有数字
String num = "";
for (int i=0;i<temp.size();i++){
num+=temp.get(i);
}
// 所有根节点到叶子节点的数字集合
list.addLast(num);
return;
} else {
// 此处应用了回溯算法,因为到叶子节点,再往回走,需要移除当前叶子节点。
temp.add(root.val);
if (root.left!=null) {
dfsfun(root.left);
temp.pollLast();
}
if (root.right!=null) {
dfsfun(root.right);
temp.pollLast();
}
}
}
public int sumNumbers(TreeNode root) {
if (root==null){
return 0;
}
dfsfun(root);
int res = 0;
for (String i:list) {
if (i!=null)
res += Integer.parseInt(i);
}
return res;
}
}