这篇主要是用先序和后序实现二叉树的创建: public class BinaryTreeNode { //结点 private String name; //结点数据 private BinaryTreeNode lchild; //左孩子 private BinaryTreeNode rchild; //右孩子 public String getName() { return name; } public void setName(String name) { this.name = name; } public BinaryTreeNode getLchild() { return lchild; } public void setLchild(BinaryTreeNode lchild) { this.lchild = lchild; } public BinaryTreeNode getRchild() { return rchild; } public void setRchild(BinaryTreeNode rchild) { this.rchild = rchild; } }
/** * 二叉树图 * 1 * 2 3 * 4 6 7 * 9 * 数组中存储形式(先序): 1 2 4 # 9 # # # 3 6 # # 7 # # * 中序不能构建二叉树 * 后序遍历构建二叉树: 左右根 必须倒序 -》 根右左 1 3 7 # # 6 # # 2 # 4 9 # # # */ public class CreateBinaryTree { public static void main(String[] args){ BinaryTreeNode t = new BinaryTreeNode(); postCreateBinaryTree(t); OperateBinaryTree.preOrderTraverse(t); } public static void preCreateBinaryTree(BinaryTreeNode t){ System.out.println("清输入结点元素:"); Scanner sc = new Scanner(System.in); String str = sc.next(); if("#".equals(str)){ t.setName(str); }else{ t.setName(str); t.setLchild(new BinaryTreeNode()); preCreateBinaryTree(t.getLchild()); t.setRchild(new BinaryTreeNode()); preCreateBinaryTree(t.getRchild()); } } //其实这也应该算是先序 根左右,根右左嘛 中序和后序不能创建二叉树,都是从孩子结点出发,如果孩子结点是# 就直接退出了 public static void postCreateBinaryTree(BinaryTreeNode t) { System.out.println("清输入结点元素:"); Scanner sc = new Scanner(System.in); String str = sc.next(); if ("#".equals(str)) { t.setName(str); } else { t.setName(str); t.setRchild(new BinaryTreeNode()); postCreateBinaryTree(t.getRchild()); t.setLchild(new BinaryTreeNode()); postCreateBinaryTree(t.getLchild()); } } }