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

来源:互联网 发布:win10不能下载软件 编辑:程序博客网 时间:2024/06/08 00:20

题目:对于一个给定的二叉树,再给定一个数值,在该二叉树中找出和为该数值的路径(所有路径)。

代码如下:

package problem2;import java.util.Iterator;import java.util.LinkedList;/** * @author Hutongling * * @time:2017年3月21日 下午4:14:50 */public class 二叉树中和为某一值的路径 {    private static void findPath(TreeNode root, int expectedSum){        if(root==null)            return;        LinkedList<Integer> path=new LinkedList<Integer>();        int currentSum=0;        findPath(root, expectedSum,path,currentSum);    }    private static void findPath(TreeNode root, int expectedSum, LinkedList<Integer> path, int currentSum) {        currentSum+=root.getValue();        path.push(root.getValue());        boolean isLeaf=(root.getLeftChild()==null && root.getRightChild()==null);        if(currentSum==expectedSum && isLeaf){            System.out.println("A path is found:");//          Iterator<Integer> iter=path.iterator();//          while(iter.hasNext())//              System.out.print(iter.next() + " ");            Object[] arrayList=path.toArray();            for(int i=arrayList.length-1;i>=0;i--)                System.out.print(arrayList[i] + " ");            System.out.println();        }        if(root.getLeftChild()!=null)            findPath(root.getLeftChild(), expectedSum, path, currentSum);        if(root.getRightChild()!=null)            findPath(root.getRightChild(), expectedSum, path, currentSum);        currentSum-=root.getValue();        path.pop();    }    public static void main(String[] args) {        TreeNode root=new TreeNode(10);        TreeNode RLeft=new TreeNode(5);        TreeNode RRight=new TreeNode(12);        TreeNode RLLeft=new TreeNode(4);        TreeNode RLRight=new TreeNode(7);        root.setLeftChild(RLeft);        root.setRightChild(RRight);        RLeft.setLeftChild(RLLeft);        RLeft.setRightChild(RLRight);        findPath(root, 22);    }}

结果如下:
A path is found:
10 5 7
A path is found:
10 12

0 0
原创粉丝点击