面试题34: 二叉树的和为某一值的路径

 

 

package April_2018;
import java.util.ArrayList;

/**
 * @Author: Allen
 * @Version:v1.00
 * @CreateData:2018年4月15日 上午10:29:24
 * 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
 * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 */
public class HeWeiMouYiZhiDeLuJing {
    public static void main(String[] args) {
        TreeNode18 node18 = new TreeNode18(10);
        TreeNode18 node185 = new TreeNode18(5);
        node18.left=node185;
        node18.right=new TreeNode18(12);
        node185.left=new TreeNode18(4);
        node185.right=new TreeNode18(7);
        Solution18 solution18 = new Solution18();
        solution18.FindPath(node18, 22);
    }
}

class TreeNode18 {
    int val = 0;
    TreeNode18 left = null;
    TreeNode18 right = null;

    public TreeNode18(int val) {
        this.val = val;
    }
}

class Solution18 {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode18 root,int target) {
        ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>();
        if(root==null)
            return resultList;
        int curSum=0;
        ArrayList<Integer> list = new ArrayList<Integer>();
        FindPathByNode(root, target, root, curSum, resultList,list);
        
        return resultList;
    }
    //考虑递归函数的结构,每个节点进入之后首先进行什么样的处理,结束的条件
    private void FindPathByNode(TreeNode18 root,int target,TreeNode18 curNode,
            int curSum, ArrayList<ArrayList<Integer>> resultList, 
            ArrayList<Integer> list ){
        list.add(curNode.val);
        curSum +=curNode.val;
        boolean isLeaf = curNode.left==null && curNode.right==null;
        
        if(isLeaf && curSum==target)
        {
            //新开辟一块内存,将该块内存的地址放入resultList中
            ArrayList<Integer> tempList = new ArrayList<Integer>();
            boolean bool = tempList.addAll(list);
            if(bool)
                resultList.add(tempList);
             /*
            原来的思路是直接更改list的引用,这种方式在方法出栈之后,对引用list的更改就无效了。
           resultList.add(list);
                  ArrayList<Integer> tempList = new ArrayList<Integer>();
                  boolean bool = tempList.addAll(list);
                  if(bool){
                      list=tempList;
                  }
        */
            
        }
        
        if(curNode.left != null){
            FindPathByNode(root,target,curNode.left,
                    curSum, resultList, list);
        }
        if(curNode.right != null){
            FindPathByNode(root,target,curNode.right,
                    curSum, resultList, list);
        }
        //出栈前进行什么操作
        list.remove(list.size()-1);
        curSum-=curNode.val;
    }
}

 

posted @ 2018-04-15 17:29  Allen101  阅读(118)  评论(0编辑  收藏  举报