/**
* 二叉树的节点结构
* @author user
*
*/
class TreeNode{
String key;
int value;
TreeNode leftNode; // 默认就是null
TreeNode rightNode;
public TreeNode(String key, int value) {
this.key = key;
this.value = value;
leftNode = null;
rightNode = null;
}
}
/**
* 二叉树的树结构
* @author user
*
*/
public class BinaryTree {
private TreeNode root;
public BinaryTree(TreeNode root) {
this.root = root;
}
// 访问节点
public void visited(TreeNode node) {
if(node != null) {
System.out.println(node.key + ":" + node.value);
}
}
// 先序遍历:使用递归
public void preOrder(TreeNode root) {
visited(root);
if(root.leftNode != null) {
preOrder(root.leftNode);
}
if(root.rightNode != null) {
preOrder(root.rightNode);
}
}
// 写完的同学尝试写一下
// 中序遍历
public void midOrder(TreeNode root) {
if(root.leftNode != null) {
midOrder(root.leftNode);
}
visited(root);
if(root.rightNode != null) {
midOrder(root.rightNode);
}
}
// 后序遍历
public void lastOrder(TreeNode root) {
if(root.leftNode != null) {
lastOrder(root.leftNode);
}
if(root.rightNode != null) {
lastOrder(root.rightNode);
}
visited(root);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode("A", 1);
TreeNode node1 = new TreeNode("B", 2);
TreeNode node2 = new TreeNode("C", 3);
TreeNode node3 = new TreeNode("D", 4);
TreeNode node4 = new TreeNode("E", 5);
TreeNode node5 = new TreeNode("F", 5);
root.leftNode = node1;
node1.leftNode = node3;
root.rightNode = node2;
node3.rightNode = node4;
node2.leftNode = node5;
BinaryTree bt = new BinaryTree(root);
bt.preOrder(root);
System.out.println("=====");
bt.midOrder(root);
System.out.println("=====");
bt.lastOrder(root);
}
}