LeetCode 39 Path Sum II
来源:互联网 发布:java api chm 中文 编辑:程序博客网 时间:2024/05/22 00:27
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum=22.
5 / \ 4 8 / / \ 11 13 4 / \ / \7 2 5 1return
[ [5,4,11,2], [5,8,4,5]]分析:
看到二叉树,想递归,
看到find all,想回溯,继而想到 DFS。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root == null) return result; List<Integer> curr = new ArrayList<Integer>(); curr.add(root.val); dfs(root, sum-root.val, curr, result); return result; } private void dfs(TreeNode node, int remain, List<Integer> curr, List<List<Integer>> result){ if(node == null) return; if(node.left==null && node.right==null && remain == 0){ result.add(new ArrayList<Integer>(curr)); return; } if(node.left != null){ curr.add(node.left.val); dfs(node.left, remain-node.left.val, curr, result); curr.remove(curr.size()-1); } if(node.right != null){ curr.add(node.right.val); dfs(node.right, remain-node.right.val, curr, result); curr.remove(curr.size()-1); } }}
0 0
- LeetCode 39 Path Sum II
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- LeetCode | Path Sum II
- 【leetcode】Path Sum II
- 关于两个变量不使用临时变量进行值交换
- Seam文件(图片)上传及相关学习记录
- spring MVC原理
- setuid()与seteuid()的区别
- WLAN一些术语和基本概念
- LeetCode 39 Path Sum II
- Delphi 比较第三方正则组件 PerlRegEx 和 官方的 RegularExpressions 速度测试
- 逗号表达式
- 2014.08.30 周六-第一个servlet程序
- 运行二级指针在单链表中进行删除操作
- Rotate List 右移字符串
- MooseFS源码分析----master服务器初始化过程
- Lua 中栈操作的C API示例
- 大放大