二叉树的三种遍历

Public class Node {
// 关键字
private int keyData;

// 其他数据
private int otherData;

// 左子节点
private Node leftNode;

// 右子节点
private Node rightNode;


public Node(int keyData, int otherDate) {
this.keyData = keyData;
this.otherData = otherDate;
}



public int getKeyData() {
return keyData;
}




public void setKeyData(int keyData) {
this.keyData = keyData;
}




public Node getLeftNode() {
return leftNode;
}




public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}




public int getOtherData() {
return otherData;
}




public void setOtherData(int otherData) {
this.otherData = otherData;
}




public Node getRightNode() {
return rightNode;
}




public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}




// 显示方法
public void display(){
System.out.println(keyData + "," + otherData);
}


}




ublic class Tree {
// 根
private Node root;


// 插入方法
public void insert(int keyData, int otherData) {
Node newNode = new Node(keyData, otherData);


// 如果说没有节点
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent;
while (true) {
parent = current;
if (keyData < current.getKeyData()) {
current = current.getLeftNode();
if (current == null) {
parent.setLeftNode(newNode);
return;
}
} else {
current = current.getRightNode();
if (current == null) {
parent.setRightNode(newNode);
return;
}
}
}
}
}


// 查找方法
public Node find(int keyData) {
Node current = root;
while (current.getKeyData() != keyData) {
if (keyData < current.getKeyData()) {
current = current.getLeftNode();
} else {
current = current.getRightNode();
}
if (current == null) {
return null;
}
}
return current;
}


// 修改方法
public void change(int keyData, int newOtherData) {
Node findNode = find(keyData);
findNode.setOtherData(newOtherData);
}


// 先序遍历
public void preOrder(Node node) {
if (node != null) {
node.display();
preOrder(node.getLeftNode());
preOrder(node.getRightNode());
}
}


// 中序遍历
public void inOrder(Node node) {
if (node != null) {
inOrder(node.getLeftNode());
node.display();
inOrder(node.getRightNode());
}
}


// 后序遍历
public void endOrder(Node node) {
if (node != null) {
endOrder(node.getLeftNode());
endOrder(node.getRightNode());
node.display();
}
}


public Node getRoot() {
return root;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值