大家好,又见面了,我是全栈君。
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 1
return
[ [5,4,11,2], [5,8,4,5] ]
给定一个二叉树和一个值。找出全部根到叶的路径和等于这个值的路径。
深度优先遍历。
public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); dfs(root,sum,ret,list); return ret; } public void dfs(TreeNode root,int sum,List<List<Integer>> ret,List<Integer> list){ if(root == null) return ; if(root.val == sum && root.left == null && root.right == null){ list.add(root.val); List<Integer> temp = new ArrayList<Integer>(list);//拷贝一份 ret.add(temp); list.remove(list.size() - 1);//再删除 return ; } list.add(root.val); dfs(root.left,sum-root.val,ret,list); dfs(root.right,sum-root.val,ret,list); list.remove(list.size() - 1); } // Definition for binary tree public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/116080.html原文链接:https://javaforall.net
