路径数字串之和

1. 问题描述:

Given a binary containing digits from 0-9 only, each root-to-leaf path 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 numbe 12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 = 25

2. 题目的意思大概是:从根节点到叶子节点的路径中,把其中的路径上的数字拼接成一个字符串形成一个数字,需要把这些所有路径上的字符串数字加起来

思路是:使用深搜的办法即可轻松解决,递归搜索左子树与右子树,当搜索到叶子节点的时候表示路径结束应该把当前形成的字符串加入到List中,等到所有的路径搜索完毕,遍历List将数字字符串转化成数字然后加起来即可

代码如下:

import java.util.ArrayList;
import java.util.List;
public class Main {
	//路径数字串之和
	static List<String> list = new ArrayList<String>();
	public static void main(String[] args) {
		TreeNode<Integer> root = new TreeNode<Integer>(1);
		TreeNode<Integer> l = new TreeNode<Integer>(2);
		TreeNode<Integer> ll = new TreeNode<Integer>(4);
		TreeNode<Integer> lr = new TreeNode<Integer>(7);
		TreeNode<Integer> r = new TreeNode<Integer>(3);
		TreeNode<Integer> rr = new TreeNode<Integer>(5);
		TreeNode<Integer> rl = new TreeNode<Integer>(8);
		root.left = l;
		root.right = r;
		l.left = ll;
		l.right = lr;
		r.right = rr;
		r.left = rl;
		int sum = setSums(root);
		System.out.println(sum);
	}
	
	static void solve(String str, TreeNode node){
		str += node.val;
		if(node.left == null && node.right == null){
			list.add(str);
			return;
		}
		if(node.left != null){
			solve(str, node.left);
		}
		if(node.right != null){
			solve(str, node.right);
		}
	}
	
	static int setSums(TreeNode root){
		if(root == null) return 0;
		solve("", root);
		int sum = 0;
		for(int i = 0; i < list.size(); i++){
			sum += Integer.parseInt(list.get(i));
		}
		return sum;
	}
}

TreeNode节点的定义如下:

public class TreeNode<T> {
   public T val;
   public TreeNode<T> left = null;
   public TreeNode<T> right = null;
   public TreeNode<T> parent = null;
   public TreeNode(T val) {
     this.val = val;
   }
   
	@Override
	public String toString() {
		return "TreeNode [val=" + val + "]";
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值