zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值得路径 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     }
  • 相关阅读:
    Nginx 配置请求响应时间
    数论筛法小结
    梅田湖种田划水摸鱼记
    好题
    奇技淫巧 (不定期更新)
    随机化算法小结(Miller Rabin,Pollard Rho, 模拟退火, 随机化贪心)
    题解 P6918 [ICPC2016 WF]Branch Assignment
    P2605 [ZJOI2010]基站选址解题思路
    题解 BZOJ 3156 防御准备
    Flutter大坑 Your Xcode project requires migration 报错大坑
  • 原文地址:https://www.cnblogs.com/music180/p/4720365.html
Copyright © 2011-2022 走看看