(一)二叉树结构示例:
二叉树中的元素11、21、31等可以存放在数组或链表里面。
(二)实现一个树:
二叉树的遍历方法:前序遍历(根-左-右)、中序遍历(左-根-右)、后序遍历(左-右-根)
结点和二叉树的定义(含遍历、查询、删除):
public class Node {
private int no;
private String name;
private Node left;
private Node right;
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
//树中每个结点要存储其他两个结点
public Node (int no,String name){
this.no=no;this.name=name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
String s="no:"+this.no+",name:"+this.name;
if (this.left!=null) {
s=s+",left:"+left.name;
}
if (this.right!=null) {
s=s+",right:"+right.name;
}
return s;
}
/*前序
* 遍历
*/
public void preList() {
System.out.println(this);
if (this.left!=null) {
this.left.preList();
}
if (this.right!=null) {
this.right.preList();
}
}
//中序遍历
public void midList() {
if (this.left!=null) {
this.left.midList();
}
System.out.println(this);
if (this.right!=null) {
this.right.midList();
}
}
//后序遍历
public void backList() {
if (this.left!=null) {
this.left.backList();
}
if (this.right!=null) {
this.right.backList();
}
System.out.println(this);
}
//根据编号对结点进行查找,同样有前中后序三种方式,下面是前序
public Node preSerach(int no) {
/*首先判断自身是不是节点
* 然后向左递归,再向右递归
*/
Node retNode=null;
if(this.no==no) {
return this;
}else if(this.left!=null) {
retNode=this.left.preSerach(no);
}
if (retNode!=null) {
return retNode;
}
if (this.right!=null) {
retNode=this.right.preSerach(no);
}
if (retNode!=null) {
return retNode;
}else {
return null;
}
}
//删除结点
public void delNode(int no) {
/*判断左节点,再判断右结点
* 如果都不是就递归
*/
if ((this.left!=null)&&(this.left.getNo()==no)) {
this.left=null;return;
}else {
this.left.delNode(no);
}
if ((this.right!=null)&&(this.right.getNo()==no)) {
this.right=null;return;
}
}
}
public class BinaryTree {
private Node root;
//root结点
public BinaryTree(Node node) {
this.root=node;
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public void preList() {
if (this.root==null) {
System.out.println("根为空,不能遍历");
}else {
root.preList();
}
}
public void midList() {
if (this.root==null) {
System.out.println("根为空,不能遍历");
}else {
root.midList();
}
}
public void backList() {
if (this.root==null) {
System.out.println("根为空,不能遍历");
}else {
root.backList();
}
}
public Node preSearch(int no) {
if (this.root==null) {
System.out.println("空二叉树");
return null;
}else {
return root.preSerach(no);
}
}
}