今天复习了一下二叉树,自己试着用代码实现了一下二叉树的创建和三种遍历,既是巩固一下二叉树的要点,也是练习一下java代码,毕竟有时间没有写代码了(都快忘了咋写了)
1.节点类
package Tree;
/**
* 节点类
*/
public class Node {
private char data; //数据就用字符表示,访问节点数据就是用打印字符代替
private Node lchild;//左节点
private Node rchild;//右节点
public Node() {
}
public char getData() {
return data;
}
public void setData(char data) {
this.data = data;
}
public Node getLchild() {
return lchild;
}
public void setLchild(Node lchild) {
this.lchild = lchild;
}
public Node getRchild() {
return rchild;
}
public void setRchild(Node rchild) {
this.rchild = rchild;
}
}
2.二叉树类和创建二叉树的方法
/**
* 二叉树类
*/
public class TreeNode {
private Node root; //根节点
private static char[] chars;//用字符数组来接收二叉树的字符序列
private static int index=0;
public TreeNode() {
Scanner sc = new Scanner(System.in);
//这里通过用前序遍历的方式创建二叉树
//所以输入的字符串序列必须的是符合前序遍历的要求
//其他后序或者中序方式的大同小异
System.out.println("输入二叉树前序遍历序列:");
chars = sc.next().toCharArray();
root = create(root);//调用创建方法
}
//使用前序遍历创建二叉树
private static Node create(Node node){
if (chars[index] == '#') { //用#字符表示空节点
index++;
return null;
}
else
{
Node newNode = new Node();
newNode.setData(chars[index++]);
newNode.setLchild(create(newNode.getLchild()));
newNode.setRchild(create(newNode.getLchild()));
return newNode;
}
}
}
3.前序,中序,后序遍历
//前序遍历
public void front(Node node){
if (node == null){
//如果节点为空则输出#字符并返回
System.out.print('#');
return;
}
else {
//节点不为空,则访问节点,同时依次遍历左节点和右节点
System.out.print(node.getData());
front(node.getLchild());
front(node.getRchild());
}
}
//中序遍历
public void centre(Node node){
if (node == null){
//如果节点为空则输出#字符并返回
System.out.print('#');
return;
}
else {
//节点不为空,继续访问左节点,至之将左节点全部访问
centre(node.getLchild());
System.out.print(node.getData());
centre(node.getRchild());
}
}
//后序遍历
public void back(Node node){
if (node == null){
//如果节点为空则输出#字符并返回
System.out.print('#');
return;
}
else {
//节点不为空,继续访问左右节点,至之将左右节点全部访问
back(node.getLchild());
back(node.getRchild());
System.out.print(node.getData());
}
}
以上就是代码实现,二叉树的遍历算是树这种数据结构中比较简单的知识点了。