剑指offer之二叉树中和为某一值的路径(Java实现)

版权声明:转载请联系 :[email protected] https://blog.csdn.net/weixin_40928253/article/details/85565709

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

NowCoder

题目描述:

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所
经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

解题思路:

import java.util.ArrayList;
public class Solution {
  private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
       private ArrayList<Integer> list = new ArrayList<Integer>();
       public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
           if(root == null) {
               return listAll;
           }
           list.add(root.val);
           target -= root.val;
           //如果是叶子节点,并且满足和为给定的那个数,则把这条路径存入list中,然后再去掉最后一次加的数返回上一个节点 
           if(target == 0 && root.left == null && root.right == null){
               //因为add添加的是引用,如果不new一个的话,后面的操作会更改这个list
               listAll.add(new ArrayList<Integer>(list));
           }
           FindPath(root.left, target);//如果没有达到上面的要求则向左子树查找  
           FindPath(root.right, target);//如果没有达到上面的要求则向右子树查找 
           list.remove(list.size()-1);//最后在向上一步,查找下一个分支  
           return listAll;
       }
}

猜你喜欢

转载自blog.csdn.net/weixin_40928253/article/details/85565709