一道很简单的题目,这里只是对比一下几种思路和做法。
题目很简单,就是一颗二叉树由0-9数字构成,求所有root->leaf路径组成的数的总和。
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
这种dfs和bfs过程都可以求解。
我自己第一时间想到的还是dfs。
dfs有两种典型做法,
第一种:由于root到当前节点的路径唯一,所以可以求得当前"root->当前节点"路径的值sum,sum传递给子节点,再求"root->子节点"的路径的sum值,主要过程:包含当前节点的所有路径值=包含左子节点所有路径值+包含右子节点所有路径值。
第二种:维持一个res值,当前节点的倍数=左节点的倍数10+右节点的倍数10,主要过程:dfs遍历所有节点,res=res + currentNode.val * currentNode.multiNum。
个人倒觉得第二种思路比较直观简单,没有同时向下传递状态和获得返回值两个方向同时进行,只是单纯的进行递归获得返回值,直接按照第二种思路来实现(省略TreeNode的结构):
public class Solution {
public int sumNumbers(TreeNode root) {
int[] res=new int[1];
res[0]=0;
if(root==null)
return 0;
dfs(root,res);
return res[0];
}
public int dfs(TreeNode root,int[] res){
int k=0;
if(root.left==null&&root.right==null)
k=1;
if(root.left!=null)
k=k+10*dfs(root.left,res);
if(root.right!=null)
k=k+10*dfs(root.right,res);
res[0]=res[0]+root.val*k;
return k;
}
}
附第一种思路的实现:
链接:https://www.nowcoder.com/questionTerminal/185a87cd29eb42049132aed873273e83
public class Solution {
private int sum;
public int sumNumbers(TreeNode root) {
StringBuilder sb = new StringBuilder();
preorder(root, sb);
return sum;
}
private void preorder(TreeNode node, StringBuilder current) {
if (node == null) {
return;
}
current.append(node.val);
if (node.left == null && node.right == null) {
sum += Integer.parseInt(current.toString());
}
preorder(node.left, current);
preorder(node.right, current);
current.deleteCharAt(current.length() - 1);
}
}
public class Solution {
public int sumNumbers(TreeNode root) {
if(root==null)
return 0;
return helper(root,0);
}
private int helper(TreeNode root,int sum){
if(root==null)
return 0;
sum=10*sum+root.val;
if(root.left==null&&root.right==null)//必须加上,如果不加,root 处的sum 为0!!!
return sum;
int left=helper(root.left,sum); //
int right=helper(root.right,sum);
return left+right;
}
}
还有回溯做法的实现:
主要过程就是维持一个StringBuilder,很典型的过程:
add current char -> next dfs -> delete current char
output string when reach end
代码实现:
链接:https://www.nowcoder.com/questionTerminal/185a87cd29eb42049132aed873273e83
public class Solution {
private int sum;
public int sumNumbers(TreeNode root) {
StringBuilder sb = new StringBuilder();
preorder(root, sb);
return sum;
}
private void preorder(TreeNode node, StringBuilder current) {
if (node == null) {
return;
}
current.append(node.val);
if (node.left == null && node.right == null) {
sum += Integer.parseInt(current.toString());
}
preorder(node.left, current);
preorder(node.right, current);
current.deleteCharAt(current.length() - 1);
}
}
比较简单基础的算法题,但却可以用上很多经典的基础算法过程。还有其它的实现,后面再补充下。