定义树结点
class TreeNode {
int val; //当前结点的值
TreeNode left; //左子结点
TreeNode right; //右子结点
//无参构造
public TreeNode() {
val = 0;
}
//有参构造方法
public TreeNode(int val) {
this.val = val;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
//前序递归
public void preOrder() {
System.out.println(this.val);
if (this.left != null) {
this.left.preOrder();
}
if (this.right != null) {
this.right.preOrder();
}
}
}
定义二叉树
class BinaryTree {
TreeNode root; //根结点
//构造器
public BinaryTree(TreeNode rootNode) {
root = rootNode;
}
//前序递归
public void preOrder() {
if (this