public class erChaShu {
public static void main(String[] args) {
Tree.insert(10);
Tree.insert(3);
Tree.insert(20);
Tree.insert(50);
Tree.insert(30);
// Tree.frontOrder(Tree.root);
// Tree.centerOrder(Tree.root);
Tree.backOrder(Tree.root);
}
}
/**
* 节点的构造
*/
class Node {
//数据域
public int val;
//左子节点
public Node leftChild;
//右子节点
public Node rightChild;
public Node(int val) {
this.val = val;
}
}
/**
* 树的构造
* @author user
*
*/
class Tree {
//根子节点
public static Node root;
/**
* 数据插入
*/
public static void insert(int value){
//构造一个结点
Node newNode = new Node(value);
//设置当前结点为根节点
Node current = root;
//父节点
Node parent;
//说明是第一次插入
if(root == null) {
root = newNode;
return;
} else {
//不是第一次插入
while(true) {
//父节点指向当前节点
parent = current;
//父节点的值大于插入的值,向左走
if(current.val > value) {
current = current.leftChild;
//为null说明走到了最左边了,可以插入了
if(current == null) {
parent.leftChild = newNode;
return;
}
//父节点的值小于插入的值,向右走
} else {
current = current.rightChild;
//走到了最右边可以插了
if(current == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
/**
* 树的遍历:前序遍历
* 根 左 右
*/
public static void frontOrder(Node localNode) {
if(localNode != null) {
System.out.println(localNode.val);
//前序遍历左子树
frontOrder(localNode.leftChild);
//前序遍历右子树
frontOrder(localNode.rightChild);
}
}
/**
* 树的遍历:中序遍历
* 左 根 右
*/
public static void centerOrder(Node localNode) {
if(localNode != null) {
//中序遍历左子树
centerOrder(localNode.leftChild);
//访问根节点
System.out.println(localNode.val);
//中序遍历右子树
centerOrder(localNode.rightChild);
}
}
/**
* 树的遍历:后序遍历
* 左 右 根
*/
public static void backOrder(Node localNode) {
if(localNode != null) {
//后序遍历左子树
backOrder(localNode.leftChild);
//后序遍历右子树
backOrder(localNode.rightChild);
//访问根节点
System.out.println(localNode.val);
}
}
}本文出自 “12212886” 博客,请务必保留此出处http://12222886.blog.51cto.com/12212886/1963554
原文:http://12222886.blog.51cto.com/12212886/1963554