LeetCode257. Binary Tree Paths

257. Binary Tree Paths

   1
 /   \
2     3
 \
  5
["1->2->5", "1->3"]

题意:
给出一个二叉树,返回所有根节点到叶子的路径

public class LeetCode257 {

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> path = new ArrayList<>();
        if(root == null) return path;
        String onepath = "";
        paths(root, onepath, path);
        return path;
    }
    public static void paths(TreeNode root, String curPath, List<String> path){
        curPath = curPath +  root.val ;
        if(root.left == null && root.right == null){    // 到达叶子节点
            path.add(curPath);
        }
        curPath = curPath + "->";
        if(root.left != null){
            paths(root.left, curPath, path);
        }
        if(root.right != null){
            paths(root.right, curPath, path);
        }
    }
}

129. Sum Root to Leaf Numbers
题意:
找到所有根到叶子的数字和
例如:

   1
 /   \
2     3

1->2 代表12
1->3 代表13
所有根到叶子的和为:12+13=25
解题思路:
思路1:和上题类似,先求出所有路径,推进一步乘以10,求出所有数字,然后相加。
思路2:递归相加

public class LeetCode129 {
    /*
    public int sumNumbers(TreeNode root) {
        List<Integer> path = new ArrayList<>();
        int res = 0;
        if(root == null) return res;
        paths(root, 0, path);
        for(Integer tmp:path){
            res = res + tmp;
            System.out.println(tmp);
        }
        return res;
    }
    public static void paths(TreeNode root, int curPath, List<Integer> path){
        curPath = curPath +  root.val ;
        if(root.left == null && root.right == null){
            path.add(curPath);
        }
        curPath = curPath * 10;
        if(root.left != null){
            paths(root.left, curPath, path);
        }
        if(root.right != null){
            paths(root.right, curPath, path);
        }
    }

    */
    public int sumNumbers(TreeNode root) {  
        return dfs(root, 0);  
    }  
    public int dfs(TreeNode root, int sum) {  
        if(root == null) return 0;  
        if(root.left == null && root.right == null) return root.val + sum * 10;           
        return dfs(root.left, root.val + sum * 10) + dfs(root.right, root.val + sum * 10);        
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值