java版本 递归树形结构的源代码
时间: 2023-03-31 11:01:57 浏览: 95
以下是 Java 版本的递归树形结构的源代码:
```
public class TreeNode {
private int val;
private TreeNode left;
private TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
public void insert(int val) {
if (val < this.val) {
if (this.left == null) {
this.left = new TreeNode(val);
} else {
this.left.insert(val);
}
} else {
if (this.right == null) {
this.right = new TreeNode(val);
} else {
this.right.insert(val);
}
}
}
public void printInOrder() {
if (this.left != null) {
this.left.printInOrder();
}
System.out.print(this.val + " ");
if (this.right != null) {
this.right.printInOrder();
}
}
}
```
希望对你有帮助!
阅读全文