输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
来源:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
学习一下遍历二叉树从根节点到叶子节点路径的问题,虽然效率不高,但是毕竟是自己写的,思路清晰,特此记录!
import java.util.ArrayList; import java.util.List; class Solution { public static void main(String[] args) { TreeNode root = new TreeNode(5); root.left = new TreeNode(4); root.right = new TreeNode(8); root.left.left = new TreeNode(11); root.left.left.left = new TreeNode(7); root.left.left.right = new TreeNode(2); root.right.left = new TreeNode(13); root.right.right = new TreeNode(4); root.right.right.left = new TreeNode(5); root.right.right.right = new TreeNode(1); List<List<Integer>> lists = new Solution().pathSum(root, 22); System.out.println(lists); } public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> lists = new ArrayList<>(); if (root==null) return lists; ArrayList<Integer> local = new ArrayList<>(); help(lists,local,root,sum); return lists; } private void help(List<List<Integer>> lists, ArrayList<Integer> local, TreeNode node, int sum) { local.add(node.val); if (node.left ==null && node.right == null){ ArrayList<Integer> oldlocal = new ArrayList<>(local); int Sum = 0; Sum = local.stream().reduce(Sum, (a, b) -> a + b); if (Sum == sum){ lists.add(oldlocal); } } if (node.left!=null) { help(lists, local, node.left, sum); local.remove(local.size() - 1); } if (node.right!=null) { help(lists, local, node.right, sum); local.remove(local.size() - 1); } } }