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



import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class Tree{
 int v;
 Tree left;
 Tree right;
}

public class PathofTree {
 
 //从数组中递归创建树,i 数组中的第i个元素,返回树的根节点
 public static Tree creat(int [] data,int i){
  if(data==null || i<0||i>=data.length){
   return null;
  }else{
   Tree root = new Tree();
   root.v=data[i];
   root.left=creat(data, (i<<1)+1);
   root.right=creat(data, (i<<1)+2);
   return root;
  }
 }
 //按层次遍历树 root树的根节点
 public static void levelPrintTree(Tree root){
  if(root==null){
   return;
  }
  Queue<Tree> queue=new LinkedList<Tree>();
  queue.add(root);
  while(!queue.isEmpty()){
   Tree node = queue.poll();
   System.out.print(node.v+"\t");
   if(node.left!=null){
    queue.add(node.left);
   }
   if(node.right!=null){
    queue.add(node.right);
   }
  }
  System.out.println();
 }
 //查找二叉树中和为某一值的路径
 public static void findPath(Tree root,int expectSum,Stack<Integer> stack,
   int currentSum){
  if(root==null){
   return;
  }
  stack.push(root.v);
  currentSum+=root.v;
  //如果是叶子节点,而且和为给定值,则打印路径
  boolean isleaf=root.left==null && root.right==null;
  if(isleaf && currentSum==expectSum){
   for(Integer e:stack){
    System.out.print(e+"\t");
   }
   System.out.println();
  }
  //如果不是叶子节点,则遍历它的子节点
  if(root.left!=null){
   findPath(root.left, expectSum, stack, currentSum);
  }
  if(root.right!=null){
   findPath(root.right, expectSum, stack, currentSum);
  }
  stack.pop();
 }

 public static void main(String[] args) {
  int data[]={10,5,12,4,7};
        Tree rootTree=creat(data, 0);
        levelPrintTree(rootTree);
        Stack<Integer> stack=new Stack<Integer>();
        findPath(rootTree, 22, stack, 0);
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值