树-Path Sum II(指定和,求根到叶子的路径)

来源:互联网 发布:java入门到精通4 pdf 编辑:程序博客网 时间:2024/06/08 16:57

题目:

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]]

思考:

想了大半天,参考了往上的办法,深度优先搜索,先从根节点的左儿子的左儿子...一直到叶子位置,那么这就是第一条路径了,路径和为参数就加入保存路径的list,否则删掉这个叶子,查看这个节点的兄弟试试看,也就是这个叶子的父节点的有儿子(有的话),采用递归,以此类推。

代码(java):

/** * Definition for a binary tree node. * 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>> totalPath = new ArrayList<List<Integer>>();int total = 0;List<Integer> currentPath = new ArrayList<Integer>();find(root, sum, currentPath, total, totalPath);return totalPath;    }                        public void find(TreeNode root, int sum, List<Integer> currentPath, int total, List<List<Integer>> totalPath){if(root == null){return;}currentPath.add(root.val);total = total + root.val;if(root.left == null && root.right == null && total == sum){totalPath.add(new ArrayList(currentPath));return;}//首先会一直遍历left,然后才是慢慢的往上走,取查看他的兄弟,所以需要删除最后一个!if(root.left != null){//currentPath.add(root.val);//total = total + root.val;find(root.left, sum, currentPath, total, totalPath);currentPath.remove(currentPath.size() - 1);}if(root.right != null){//currentPath.add(root.val);//total = total + root.val;find(root.right, sum, currentPath, total, totalPath);currentPath.remove(currentPath.size() - 1);}}}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 bbox吸管杯漏水怎么办 四个月宝宝拉肚子怎么办 租的房子坐月子怎么办 榨果汁不甜怎么办 宝宝不会喝奶粉怎么办 两个月宝宝不长肉怎么办 打疫苗后发烧怎么办 孕期不爱吃水果怎么办 孕期很少吃水果怎么办 三个月小孩不吃奶粉怎么办 三个月宝宝偏瘦怎么办 破壁机打果汁有沫怎么办 宝宝7个月坐不稳怎么办 婴儿头睡偏了怎么办天 宝宝不爱趴着怎么办 宝宝喜欢竖着抱怎么办 婴儿抱习惯了怎么办 新生儿总让抱着放下就哭可怎么办 三个月宝宝认人怎么办 三个月的宝宝认生怎么办 一岁半宝宝尿黄怎么办 一岁多宝宝尿少怎么办 1岁宝宝一晚没尿怎么办 抗利尿激素少怎么办 小孩夜里尿多怎么办 一岁宝宝认生怎么办 婴儿一个月认生怎么办 婴儿大便带血丝怎么办 两个月宝宝认生怎么办 晚上宝宝认人怎么办 小孩长白头发怎么办 三个月婴儿脚力不足怎么办 未满月宝宝便秘怎么办 婴儿5天没拉大便怎么办 儿童三天没大便怎么办 婴儿4天没拉大便了怎么办 孩子不天天排便怎么办 宝宝便秘5天怎么办 小孩子3天便秘怎么办 宝宝4天没拉大便怎么办 儿童不拉大便怎么办