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

本题来自《剑指offer》

  路径为从根节点到叶节点一条路径,路径经过的各节点数值之和等于某一给定数值,则打印路径上的节点

  • 因为需要打印满足条件的路径节点信息和各节点之和,需要栈记录经过的节点,和一个保存数值之和的变量
  • 用前序遍历方法,可以首先访问节点,然后将节点入栈,并将数值和之前入栈的节点值相加
  • 如果当前之和否满足给定值,判断当前节点是否叶节点,是则打印路径信息
  • 判断节点左右孩子是否为空,递归调用
  • 在调用完,返回时要将入栈的值出栈(此时栈中节点只到父节点),和变量也要变回调用之前的状态
  •   

     1     //二叉树定义
     2     class Btree {
     3         int value;
     4         Btree leftBtree;
     5         Btree rightBtree;
     6     }
     7     private Stack<Integer> stack = new Stack<Integer>(); 
     8     public void FindPath(Btree node , int sum,int currSum){
     9         boolean isLeaf;
    10         if(node == null)
    11             return;
    12         currSum += node.value;
    13         stack.push(node.value);
    14         isLeaf = node.leftBtree == null && node.rightBtree == null;
    15         if(currSum == sum && isLeaf){
    16             System.out.println("Path:");
    17             for(int val : stack){
    18                 System.out.println(val);
    19             }
    20         }
    21         if(node.leftBtree != null)
    22             FindPath(node.leftBtree, sum, currSum);
    23         if(node.rightBtree != null)
    24             FindPath(node.rightBtree, sum, currSum);
    25         currSum -= node.value;
    26         stack.pop();
    27     }

     

 

posted @ 2015-08-11 10:47  music180  阅读(1544)  评论(0编辑  收藏  举报