剑指offer 24.举例让抽象具体化 二叉树中和为某一值的路径

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
 
牛客大神解题思路如下:
emmmmmmmmmmmmmmmmmmmmmmmmmm
不好意思,看不懂大神的思路
不过代码好精辟好简洁
虽然看不懂但是觉得很厉害
 
这是大概思路

* FindPath功能:在给定root子树中,找出合理的路径以达到目标和target 
  * FindPath实质:二叉树的深度优先遍历 + 每次遍历均判断是否达到条件,若是则输出
  * 大致策略
  * 1、root入栈,跳入该子树进行寻路操作 
  * 2、若root的这条路径,已满足要求,则将该路径加入到listAll中去
  * 3、对root左右子树,继续寻路
  * 4、root出栈,该子树访问完毕
 
 
代码如下:

package jianzhioffer.tree;

import java.util.ArrayList;

/**
*
* @author hadoop
*
*/

public class FindPath {
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;
if(target == 0 && root.left == null && root.right == null)
listAll.add(new ArrayList<Integer>(list));
FindPath(root.left, target);
FindPath(root.right, target);
list.remove(list.size()-1);
return listAll;
}

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

public TreeNode(int val) {
this.val = val;

}

}

}


以下为比较容易理解的答案:

代码如下:


import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,
            int target) {
        ArrayList<ArrayList<Integer>> pathList=
                new ArrayList<ArrayList<Integer>>();
        if(root==null)
            return pathList;
        Stack<Integer> stack=new Stack<Integer>();
        FindPath(root,target,stack,pathList );
        return pathList;
         
    }
    private void FindPath(TreeNode root, int target,
            Stack<Integer> path,
            ArrayList<ArrayList<Integer>> pathList) {
        if(root==null)
            return;
        if(root.left==null&&root.right==null){
            if(root.val==target){
                ArrayList<Integer> list=
                        new ArrayList<Integer>();
                for(int i:path){
                    list.add(new Integer(i));
                }
                list.add(new Integer(root.val));
                pathList.add(list);
            }
        }
        else{
            path.push(new Integer(root.val));
            FindPath(root.left, target-root.val, path, pathList);
            FindPath(root.right, target-root.val, path,  pathList);
            path.pop();
        }
         
    }
}
原文地址:https://www.cnblogs.com/Transkai/p/10929676.html