一、示例:

树的结构:

示例中自己构建了图片中的这棵树:

树节点模型:

public class TreeNode {String value;List<TreeNode> children;public TreeNode() {children = new ArrayList<>();}public TreeNode(String value) {this.value = value;children = new ArrayList<>();}@Overridepublic String toString() {// TODO Auto-generated method stubreturn value;}
}

构建树:

// 创建一棵树
TreeNode root = new TreeNode("A");
// 第二层
root.children.add(new TreeNode("B"));
root.children.add(new TreeNode("C"));
// 第三层
root.children.get(0).children.add(new TreeNode("D"));
root.children.get(0).children.add(new TreeNode("E"));
root.children.get(1).children.add(new TreeNode("F"));
root.children.get(1).children.add(new TreeNode("H"));
root.children.get(1).children.add(new TreeNode("G"));
// 第四层
root.children.get(0).children.get(1).children.add(new TreeNode("I"));

二、遍历方式

提供三种方式进行遍历:

① 递归形式的深度优先遍历:

/*** 深度优先遍历(递归方式) --- 树(Tree)*/public void recurTree(TreeNode root) {List<List<String>> result = new ArrayList<>();List<String> path = new ArrayList<>();path.add(root.value);findPath(result, root, path);System.out.println(result);}private void findPath(List<List<String>> result, TreeNode node, List<String> path) {if (node.children == null || node.children.size() <= 0) {result.add(path);return;}for (int i = 0; i < node.children.size(); i++) {TreeNode child = node.children.get(i);List<String> cPath = new ArrayList<>();cPath.addAll(path);cPath.add(child.value);findPath(result, child, cPath, target);}}

② 非递归的深度优先遍历

/*** 深度优先遍历(非递归方式) ----- 查找树的所有叶子路径* * @param root*            根节点* @return 叶子路径的集合*/public List<List<TreeNode>> dfsTree(TreeNode root) {Stack<TreeNode> nodeStack = new Stack<>();Stack<List<TreeNode>> pathStack = new Stack<>();List<List<TreeNode>> result = new ArrayList<>();nodeStack.push(root);ArrayList<TreeNode> arrayList = new ArrayList<>();arrayList.add(root);pathStack.push(arrayList);while (!nodeStack.isEmpty()) {TreeNode curNode = nodeStack.pop();List<TreeNode> curPath = pathStack.pop();if (curNode.children == null || curNode.children.size() <= 0) {result.add(curPath);} else {int childSize = curNode.children.size();for (int i = childSize - 1; i >= 0; i--) {TreeNode node = curNode.children.get(i);nodeStack.push(node);List<TreeNode> list = new ArrayList<>(curPath);list.add(node);pathStack.push(list);}}}return result;}

3. 广度优先遍历,遍历所有叶子路径

/*** 广度优先遍历 ---- 查找树的所有叶子路径* * @param root*            根节点* @return 叶子路径的集合*/public List<List<TreeNode>> bfsTree(TreeNode root) {Queue<TreeNode> nodeQueue = new LinkedList<>();Queue<List<TreeNode>> qstr = new LinkedList<>();List<List<TreeNode>> result = new ArrayList<>();nodeQueue.add(root);ArrayList<TreeNode> arrayList = new ArrayList<>();qstr.add(arrayList);while (!nodeQueue.isEmpty()) {TreeNode curNode = nodeQueue.remove();List<TreeNode> curList = qstr.remove();if (curNode.children == null || curNode.children.size() <= 0) {curList.add(curNode);result.add(curList);} else {for (int i = 0; i < curNode.children.size(); i++) {TreeNode treeNode = curNode.children.get(i);nodeQueue.add(treeNode);List<TreeNode> list = new ArrayList<>(curList);list.add(curNode);qstr.add(list);}}}return result;}

三种方式的输出:

深度优先遍历(递归):[[A, B, D], [A, B, E, I], [A, C, F], [A, C, H], [A, C, G]]
广度优先遍历:[[A, B, D], [A, C, F], [A, C, H], [A, C, G], [A, B, E, I]]
深度优先遍历(非递归):[[A, B, D], [A, B, E, I], [A, C, F], [A, C, H], [A, C, G]]

三、总结

  示例是查找树的所有叶子节点,举一反三,如果我们是查找树中满足某个条件的路径,也是非常容易了。比如下面中查找 “ E ” 的分支:

public void recurTree(TreeNode root) {List<List<String>> result = new ArrayList<>();List<String> path = new ArrayList<>();path.add(root.value);findPath(result, root, path, "E");System.out.println(result);}private void findPath(List<List<String>> result, TreeNode node, List<String> path, String target) {if (target.equals(node.value)) {result.add(path);return;}if (node.children == null || node.children.size() <= 0) {return;}for (int i = 0; i < node.children.size(); i++) {TreeNode child = node.children.get(i);List<String> cPath = new ArrayList<>();cPath.addAll(path);cPath.add(child.value);if (result.size() > 0)break;findPath(result, child, cPath, target);}}

输出:

[[A, B, E]]

转载于:https://www.cnblogs.com/aimqqroad-13/p/10238093.html

遍历树,找出所有叶子路径相关推荐

  1. python遍历文件夹下所有文件名中含有指定_Python 遍历目录找出包含指定字符串的文件夹...

    题目:编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径 题目不难,但是初接触Python,对函数不够熟悉,犯了不少错误.总结如下: os.path. ...

  2. android 遍历所有view,Android 算法:遍历ViewGroup找出所有子View

    1.用递归的方式实现 // 遍历viewGroup public int traverseViewGroup(View view) { int viewCount = 0; if (null == v ...

  3. 解放文件夹下所有层级的特定格式文件,找出文件夹内所有的txt/FLAC/MP4/MP3等等等等,并复制到另一个文件夹中

    解放文件夹下所有层级的特定格式文件,找出文件夹内所有的txt/FLAC/MP4/MP3等等等等,并复制到另一个文件夹中 引言 代码 得意 天天学习,好好向上 引言 各位朋友们好!最近遇到一些想要方便办 ...

  4. python取出字典中最大值_python找出字典中value最大值的几种方法

    假设定义一字典,m = {"a":3,"e":6,"b":2,"g":7,"f":7,"c ...

  5. python字典找出年龄最大的人_python找出字典中value最大值的几种方法

    假设定义一字典,m = {"a":3,"e":6,"b":2,"g":7,"f":7,"c ...

  6. 程序员面试题经典问题——耶稣有13个门徒,其中有一个就是出卖耶稣的叛徒,请用排除法找出这位叛徒:13人围坐一圈,从第一个开始报号:123凡是报到“3”就退出圈子,最后留在圈子内的人就是出卖耶稣的叛徒。

    package com.softeem.project1;public class Test1 {public static void main(String[] args) {//定义数组保存13位 ...

  7. 给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。...

    给定两个字符串 s 和 t,它们只包含小写字母.字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母.请找出在 t 中被添加的字母. 示例: 输入: s = "abcd" ...

  8. 【练习】树(Tree, UVa 548)给一棵点带权(权值各不相同)的二叉树的中序和后序遍历,找一个叶子使得它到根的路径上的权和最小。

    给一棵点带权(权值各不相同,都是小于10000的正整数)的二叉树的中序和后序遍历,找一个叶子使得它到根的路径上的权和最小.如果有多解,该叶子本身的权应尽量小.输入中每两行表示一棵树,其中第一行为中序遍 ...

  9. 常考数据结构与算法----给定一个二叉树和一个值 sum,请找出所有的根节点到叶子节点的节点值之和等于sum 的路径,

    题目描述 给定一个二叉树和一个值sum,请找出所有的根节点到叶子节点的节点值之和等于sum 的路径, 例如: 给出如下的二叉树,sum=22, 返回 [ [5,4,11,2], [5,8,9] ] 示 ...

最新文章

  1. 一道非常经典C++面试题|大厂面试
  2. Java集合框架:LinkedList
  3. python基础(part14)--异常处理
  4. JavaScript:通过id来进行元素的取得
  5. eclipse调试第一个java程序
  6. 为什么jvm要分为堆、方法区等?原理是什么?_「JVM」知识点详解一:JVM运行原理详解...
  7. mysql的dql_Mysql-DQL
  8. css 将图片折角,纯css3实现的折角效果(无需图片和js代码)
  9. cms,crm名词解释
  10. r230服务器装系统教程,DELL r230 安装centos7.4记录
  11. 仓库防霉防潮作业指导书
  12. LocalDate、LocalDateTime计算时间差
  13. Cesium 可视域分析代码段(源码)补充
  14. 软件工程结对开发——返回一个整数数组中最大子数组的和(JAVA)
  15. VOT 2015 Benchmark 使用教程
  16. 假面舞会狂欢节·圆桌 | 当Thinker遇上Artist
  17. java 实习生刚入职都会做些什么工作呢?
  18. JS原型和原型链是什么?
  19. 漫谈大数据 - Spark on Hive Hive on Spark
  20. win10 该文件没有与之关联的应用来执行该操作。请安装应用...

热门文章

  1. java输入验证码代码,JavaWeb 实现验证码功能(demo)
  2. 思科路由器Ez×××解决地址重叠测试
  3. spring aop如何在切面类中获取切入点相关方法的参数、方法名、返回值、异常等信息
  4. springMVC结合jersey实现跨服务器文件上传
  5. HDU-3337 Guess the number 测试输入数据
  6. 手机发包工具_【发包工具】http多线程发包工具
  7. rust货轮什么时候出现_婴儿什么时候用枕头合适?并非三个月,出现以下征兆再用不迟...
  8. 2020-09-08 Win7-Win10内部版本号
  9. 新编译的GDAL1.9 C/C++ C# Python版本
  10. Netty的使用:Server和Client通信