leedcode做题总结,题目Sum Root to Leaf Numbers 2013/02/18

本文介绍了一种解决二叉树路径之和问题的方法,利用递归遍历二叉树的所有路径,并计算从根节点到叶子节点路径所代表数字的总和。提供了两种解决方案:一种是使用栈和链表来存储路径,另一种是采用简洁的回溯法。

这个题的意思是每条root到leaf的路径当成一个数,然后计算所有路径所代表的数的和。

树的路径最好用的就是递归,每个节点返回一个栈,栈里包含所有路径的linkedlist。


public Stack<LinkedList> sumNum(TreeNode root) {
        if(root.left==null&root.right==null){
            LinkedList<Integer> l = new LinkedList<Integer>();
            l.add(root.val);
            Stack<LinkedList> s = new Stack<LinkedList>();
            s.push(l);
            return s;
        }
        Stack<LinkedList> s = new Stack<LinkedList>();
        if(root.left!=null){
            Stack<LinkedList> s1 = sumNum(root.left);
            while(!s1.isEmpty()){
                LinkedList<Integer> l=s1.pop();
                l.add(root.val);
                s.push(l);
            }
        }
        if(root.right!=null){
            Stack<LinkedList> s2 = sumNum(root.right);
            while(!s2.isEmpty()){
                LinkedList<Integer> l=s2.pop();
                l.add(root.val);
                s.push(l);
            }
        }
        return s;
    }
    public int sumNumbers(TreeNode root) {
        if(root==null) return 0;
        Stack<LinkedList> s = sumNum(root);
        int sum=0;
        while(!s.isEmpty()){
            LinkedList<Integer> l=s.pop();
            int ji=1;
            while(!l.isEmpty()){
                int zhi = l.removeFirst();
                sum = sum+zhi*ji;
                ji=ji*10;
            }
        }
        return sum;
    }

Update 2015/08/18: 上面的解法很复杂,其实这道题用回溯法即可:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int check(TreeNode root, int tmp, int res){
        if (root == null)
            return 0;
        tmp = tmp * 10 + root.val;
        if (root.left == null && root.right == null){
            res += tmp;
        }
        int a = check(root.left, tmp, res);
        int b = check(root.right, tmp, res);
        tmp = (tmp - root.val) / 10;
        return res + a + b;
    }
    public int sumNumbers(TreeNode root) {
        return check(root, 0, 0);
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值