📄 tree.java
字号:
/** Tree.java **************/
package binarytree;
public class Tree extends Component {
private String name;
private Component leftChild;
private Component rightChild;
public Tree(String name, Component leftChild, Component rightChild) {
this.name = name;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public Tree(String name) {
this.name = name;
this.leftChild = null;
this.rightChild = null;
}
public Component addChild(Component leftChild, Component rightChild) {
this.leftChild = leftChild;
this.rightChild = rightChild;
return this;
}
public String getName() {
return name;
}
public void getTreeInfo()
//得到树或叶子的详细信息
//先打印自己的名字,再遍例左孩子,再遍例右孩子
//如果左孩子或右孩子是树,递归调用
{
System.out.println(" this trees name is " + getName());
if (this.leftChild instanceof Leaf) {
System.out.println(getName() + "s left child is " +
this.leftChild.getName() + ",it is a Leaf");
}
if (this.leftChild instanceof Tree) {
System.out.println(getName() + "s left child is " +
this.leftChild.getName() + ",it is a Tree");
this.leftChild.getTreeInfo();
}
if (this.leftChild == null) {
System.out.println(getName() + "s left child is a null");
}
if (this.rightChild instanceof Leaf) {
System.out.println(getName() + "s right child is " +
this.rightChild.getName() + ",it is a Leaf");
}
if (this.rightChild instanceof Tree) {
System.out.println(getName() + "s right child is " +
this.rightChild.getName() + ",it is a Tree");
this.rightChild.getTreeInfo();
}
if (this.rightChild == null) {
System.out.println(getName() + "s right child is a null");
}
//System.out.println(getName()+"s 高度 是 "+getLength());
}
public int getLength() {
//比较左孩子或右孩子的高度,谁大,+1 返回
// 空孩子的处理
if (this.leftChild == null) {
if (this.rightChild == null)
return 1;
else
return this.rightChild.getLength() + 1;
} else {
if (this.rightChild == null) {
return this.leftChild.getLength() + 1;
} else {
if ((this.leftChild.getLength()) >= (this.rightChild.getLength()))
return this.leftChild.getLength() + 1;
else
return this.rightChild.getLength() + 1;
}
}
}
public static void main(String[] args) {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -