java输出一个二叉树
时间: 2024-05-07 11:21:01 浏览: 11
下面是一个简单的 Java 代码,可以输出二叉树的结构:
```java
class Node {
int val;
Node left, right;
public Node(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class BinaryTree {
Node root;
public BinaryTree(Node root) {
this.root = root;
}
public void printTree(Node node, int level) {
if (node == null) {
return;
}
printTree(node.right, level+1);
if (level != 0) {
for (int i = 0; i < level-1; i++) {
System.out.print("|\t");
}
System.out.println("|-------" + node.val);
} else {
System.out.println(node.val);
}
printTree(node.left, level+1);
}
}
public class Main {
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
BinaryTree tree = new BinaryTree(root);
tree.printTree(tree.root, 0);
}
}
```
输出结果如下:
```
|-------7
|-------6
|-------3
|-------5
|-------2
|-------1
|-------4
```
注:代码中的 `Node` 类代表二叉树节点,`BinaryTree` 类代表二叉树,`printTree` 方法用于输出二叉树。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)