zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值的路径

    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
     1 import java.util.ArrayList;
     2 import java.util.Stack;
     3 public class Solution {
     4     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,
     5             int target) {
     6         ArrayList<ArrayList<Integer>> pathList=
     7                 new ArrayList<ArrayList<Integer>>();
     8         if(root==null)
     9             return pathList;
    10         Stack<Integer> stack=new Stack<Integer>();
    11         FindPath(root,target,stack,pathList );
    12         return pathList;
    13          
    14     }
    15     private void FindPath(TreeNode root, int target,
    16             Stack<Integer> path,
    17             ArrayList<ArrayList<Integer>> pathList) {
    18         if(root==null)
    19             return;
    20         if(root.left==null&&root.right==null){
    21             if(root.val==target){
    22                 ArrayList<Integer> list=
    23                         new ArrayList<Integer>();
    24                 for(int i:path){
    25                     list.add(new Integer(i));
    26                 }
    27                 list.add(new Integer(root.val));
    28                 pathList.add(list);
    29             }
    30         }
    31         else{
    32             path.push(new Integer(root.val));
    33             FindPath(root.left, target-root.val, path, pathList);
    34             FindPath(root.right, target-root.val, path,  pathList);
    35             path.pop();
    36         }
    37          
    38     }
    39 }

    这个代码不太懂!

  • 相关阅读:
    用mvc实现增删查改
    hibernate Annotation版本的helloworld
    hibernate 级联操作
    Hibrenate一对一外键关联
    hibernate主键生成
    Action属性接收参数
    WildCard的使用
    Struts 路径分析以及是否一定要执行excute()方法
    学习Struts2经验总结
    基于Struts分层web框架,研究传值问题
  • 原文地址:https://www.cnblogs.com/LoganChen/p/6432895.html
Copyright © 2011-2022 走看看