题目:
输入一颗二叉树和一个整数,打印出二叉树中节点值得和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
package hh;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
/**
*
* 二叉树
* @author Dell
*
*/
class TreeNode1{
public TreeNode1 left=null;
public TreeNode1 right=null;
public int val;
public int flag;
public TreeNode1(int val)
{
this.val=val;
}
}
public class Test72 {
public static TreeNode1 creatTree(TreeNode1 root)
{
Scanner sc=null;
sc=new Scanner(System.in);
root=Creat(root,sc);
return root;
}
public static TreeNode1 Creat(TreeNode1 root, Scanner sc) {
String temp=sc.next();
if(temp.trim().equals("#"))
{
return null;
}
else
{
root=new TreeNode1(Integer.parseInt(temp.trim()));
root.left=Creat(root.left,sc);
root.right=Creat(root.right,sc);
}
return root;
}
public static void preorder(TreeNode1 t)
{
if(t!=null)
{
System.out.print(t.val+" ");
preorder(t.left);
preorder(t.right);
}
}
public static List<List<TreeNode1>> findpath(TreeNode1 root, int target)
{
List<List<TreeNode1>> result=new ArrayList<>();
if(root==null)
return result;
List<TreeNode1> list=new ArrayList<>();
Stack<TreeNode1> s=new Stack<>();
TreeNode1 p=root;
while(p!=null||s.isEmpty()!=true)
{
if(p!=null)
{
s.push(p);
p.flag=0;
p=p.left;
}
else
{
TreeNode1 temp=s.peek();
if(temp.flag==1)
{
if(temp.left==null&&temp.right==null)
{
int sum=0;
while(s.isEmpty()!=true)
{
TreeNode1 tt=s.pop();
list.add(tt);
sum=sum+tt.val;
}
for(int i=list.size()-1;i>=1;i--)
{
s.push(list.get(i));
}
if(sum==target)
{
result.add(list);
list=new ArrayList<>();
}
list.clear();
}
else
{
s.pop();
}
}
else
{
p=temp.right;
temp.flag=1;
}
}
}
return result;
}
public static void main(String[] args) {
TreeNode1 t=null;
t=creatTree(t);
// preorder(t);
//System.out.println();
int target=22;
List<List<TreeNode1>> result=findpath(t,target);
for(int i=0;i<result.size();i++)
{
for(int j=result.get(i).size()-1;j>=0;j--)
{
System.out.print(result.get(i).get(j).val+" ");
}
System.out.println();
}
}
}