码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树中和为某一值的路径

时间:2019-01-25 18:46:37      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:一个   arraylist   val   遍历   调整   target   add   public   array   

题目:输入一颗二叉树和一个整数,打印出二叉树中节点的值的和为输入整数的是所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

 1 public class Solution {
 2     ArrayList<Integer> path = new ArrayList<Integer>();
 3     ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
 4 
 5 
 6     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
 7         if(root == null) {
 8             return list;
 9         }
10 
11         // 每访问一个结点的时候,都把当前结点添加到路径中,并调整target的值
12         path.add(root.val);
13         target = target - root.val;
14 
15         // 已经到了叶节点,并且path中的值和为target,则把当前path添加到输出列表中
16         if(target == 0 && root.left == null && root.right == null) {
17             list.add(new ArrayList<Integer>(path));
18         }
19 
20         // 否则继续遍历
21         FindPath(root.left, target);
22         FindPath(root.right, target);
23 
24         // 已到叶节点之后会跳过两个递归函数到这里,此时要把最后一个结点从路径中删除,才能返回上层结点
25         path.remove(path.size()-1);
26         return list;
27 
28     }
29 }

 

二叉树中和为某一值的路径

标签:一个   arraylist   val   遍历   调整   target   add   public   array   

原文地址:https://www.cnblogs.com/wylwyl/p/10321033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!