输入一颗二叉树和一个值,打印出和为该值的所有路径。从树的根节点开始往下直到叶节点所经历过的节点形成的一条路径。
方法:前序遍历法
void FindPath ( BiinaryTreeNode pRoot, int k){ if(pRoot==null) return; List<Integer> path= new ArrayList<Integer>(); int x=0; FindPath( pRoot , k , path , x); } void FindPath ( BiinaryTreeNode pRoot, int k , List<Integer> path, int x){ x+=pRoot.value; path.add( pRoot.value); //到达叶子结点 if( x=k && pRoot.Left==null && pRoot.Right==null){ //输出路径 for(int i=0;i<path.size();i++) System.out.print( path.get(i)); System.out.println(); } if(pRoot.Left!=null) FindPath( pRoot.Left , k , path , x); if(pRoot.Right!=null) FindPath( pRoot.Right , k , path , x); //返回节点之前删除在路径上当前节点 path.remove( path.size()-1); }