Java实现打印二叉树所有路径的方法
作者:sam_justin 时间:2021-07-13 15:52:57
本文实例讲述了Java实现打印二叉树所有路径的方法。分享给大家供大家参考,具体如下:
问题:
给一个二叉树,把所有的路径都打印出来。
比如,对于下面这个二叉树,它所有的路径为:
8 -> 3 -> 1
8 -> 2 -> 6 -> 4
8 -> 3 -> 6 -> 7
8 -> 10 -> 14 -> 13
思路:
从根节点开始,把自己的值放在一个数组里,然后把这个数组传给它的子节点,子节点同样把自己的值放在这个数组里,又传给自己的子节点,直到这个节点是叶节点,然后把这个数组打印出来。所以,我们这里要用到递归。
代码:
/**
Given a binary tree, prints out all of its root-to-leaf
paths, one per line. Uses a recursive helper to do the work.
*/
public void printPaths(Node root, int n) {
String[] path = new String[n];
printPaths(root, path, 0);
}
/**
Recursive printPaths helper -- given a node, and an array containing
the path from the root node up to but not including this node,
prints out all the root-leaf paths.
*/
private void printPaths(Node node, String[] path, int pathLen) {
if (node == null) return;
// append this node to the path array
path[pathLen++] = node.value;
// it's a leaf, so print the path that led to here
if (node.leftChild == null && node.rightChild == null) {
printArray(path, pathLen);
}
else {
// otherwise try both subtrees
printPaths(node.leftChild, path, pathLen);
printPaths(node.rightChild, path, pathLen);
}
}
/**
Utility that prints strings from an array on one line.
*/
private void printArray(String[] ints, int len) {
for (int i = 0; i < len; i++) {
System.out.print(ints[i] + " ");
}
System.out.println();
}
备注:这里只能用一个数组+一个数值才能打印出所需要的路径,如果用linkedlist之类的链表结构是不行的。值得分析一下原因,很有意思。
希望本文所述对大家java程序设计有所帮助。
来源:http://blog.csdn.net/samjustin1/article/details/52561831
标签:Java,二叉树
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
10种简单的Java性能优化
2023-06-20 20:43:41
![](https://img.aspxhome.com/file/2023/6/57526_0s.png)
C# 调用C++写的dll的实现方法
2022-10-25 11:36:56
Springboot与vue实现数据导出方法具体介绍
2023-11-06 21:00:34
详解SpringBoot注册Windows服务和启动报错的原因
2022-12-28 17:10:09
![](https://img.aspxhome.com/file/2023/1/63431_0s.jpg)
Spring Boot实现文件上传下载
2021-11-22 21:19:36
![](https://img.aspxhome.com/file/2023/3/71693_0s.jpg)
Java实战之酒店人事管理系统的实现
2021-06-02 16:44:37
![](https://img.aspxhome.com/file/2023/0/71200_0s.jpg)
C#字符集编码的使用及说明
2023-12-05 02:06:05
![](https://img.aspxhome.com/file/2023/3/78113_0s.png)
C#之继承实现
2023-04-10 16:51:41
java网络编程基础知识介绍
2023-01-10 20:37:44
![](https://img.aspxhome.com/file/2023/7/77987_0s.jpg)
深入谈谈C#9新特性的实际运用
2021-05-26 16:08:23
Java算法之递归算法计算阶乘
2021-06-30 14:10:56
![](https://img.aspxhome.com/file/2023/4/63454_0s.png)
Java多线程 自定义线程池详情
2022-12-02 09:22:08
JPA配置方式+逆向工程映射到Entity实体类
2023-07-28 12:09:48
![](https://img.aspxhome.com/file/2023/2/57942_0s.png)
Tomcat内存溢出分析及解决方法
2023-11-12 23:24:47
java实现短地址服务的方法(附代码)
2023-11-15 19:13:41
![](https://img.aspxhome.com/file/2023/5/59525_0s.png)
SpringBoot整合mybatis的方法详解
2023-09-02 06:23:57
![](https://img.aspxhome.com/file/2023/5/58455_0s.png)
Java实现简单的飞机大战游戏(控制主飞机篇)
2023-11-14 13:52:56
详解Java Selenium中的鼠标控制操作
2023-11-23 14:43:17
Java设计模式之建造者模式的示例详解
2022-02-13 18:47:34
![](https://img.aspxhome.com/file/2023/2/82452_0s.jpg)
Maven引入外部jar的几种方法(小结)
2022-11-10 01:35:30