java如何打印输出二叉树
时间: 2024-05-17 18:09:30 浏览: 17
在Java中,可以使用递归的方式打印输出二叉树。以下是一个示例代码:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreePrinter {
public static void printTree(TreeNode root) {
printTreeHelper(root, 0);
}
private static void printTreeHelper(TreeNode node, int level) {
if (node == null) {
return;
}
printTreeHelper(node.right, level + 1);
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(node.val);
printTreeHelper(node.left, level + 1);
}
public static void main(String[] args) {
// 创建一个二叉树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// 打印输出二叉树
printTree(root);
}
}
```
上述代码中,我们定义了一个`TreeNode`类来表示二叉树的节点。然后,我们编写了一个`BinaryTreePrinter`类,其中的`printTree`方法用于打印输出二叉树。`printTreeHelper`方法是一个辅助方法,使用递归的方式进行深度优先遍历,并在每个节点处打印输出节点的值。
在`main`方法中,我们创建了一个简单的二叉树,并调用`printTree`方法来打印输出该二叉树。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)