剑指offer-面试题34:二叉树中和为某一值的路径

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


public class TreeNode {
    int value = 0;
    TreeNode leftNode = null;
    TreeNode rightNode = null;

    public TreeNode(int value ) {
        this.value = value ;
    }
}
public class Solution
{
    //定义一个成员变量用于保存每一个满足条件的路径
     ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
     //定义一个成员变量用于保存每一个路径下的值
     ArrayList<Integer> path = new ArrayList<Integer>();
     public  ArrayList<ArrayList<Integer>> pathList  FindPath(TreeNode root, int target)
     {
            if(root == null)   return pathList ;
            path.add(root.value);
            target -= root.value;
            if(target ==0 && root.leftNode == null && root.rightNode == null)
            {
                  pathList.add(new ArrayList<Integer>(path));
            }
            if(root.leftNode != null)
            {
                  FindPath(root.leftNode, target);
            }
            if(root.rightNode != null)
            {
                FindPath(root.rightNode, target);
            }
            path.remove(path.size() -1);
            return pathList;
     }
}

猜你喜欢

转载自blog.csdn.net/rodman177/article/details/89762223
今日推荐