package testcase; import java.util.ArrayList; /** * * @decription 二叉树的构建以及先中后序遍历 * @author bjliuzezhou * @date 2016年2月23日 */ public class TypicalArithmetic_03 { public static void main(String[] args) { TypicalArithmetic_03 offer = new TypicalArithmetic_03(); TypicalArithmetic_03.Node root = offer.new Node(10,"root"); TypicalArithmetic_03.Node a = offer.new Node(5,"a"); TypicalArithmetic_03.Node b = offer.new Node(6,"b"); TypicalArithmetic_03.Node c = offer.new Node(1,"c"); TypicalArithmetic_03.Node d = offer.new Node(62,"d"); TypicalArithmetic_03.Node e = offer.new Node(55,"e"); TypicalArithmetic_03.Node f = offer.new Node(66,"f"); TypicalArithmetic_03.Node g = offer.new Node(6,"g"); ArrayList<Node> binaryNodes = new ArrayList<Node>(); binaryNodes.add(a); binaryNodes.add(b); binaryNodes.add(c); binaryNodes.add(d); binaryNodes.add(e); binaryNodes.add(f); binaryNodes.add(g); for(Node node : binaryNodes){ offer.buildTree(root, node); } offer.InOrder(root); } class Node{ Node(int value,String name){ this.value = value; this.name = name; } Node left; Node right; int value; String name; public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } } public void buildTree(Node root,Node node){ if(root == null){ root = node; }else{ if(root.value >= node.value){ if(root.left == null) root.left = node; else buildTree(root.left,node); }else{ if(root.right ==null) root.right = node; else buildTree(root.right,node); } } } public void preOrder(Node root){ if(root != null){ System.out.println(root.value); preOrder(root.left); preOrder(root.right); } } public void InOrder(Node root){ if(root != null){ InOrder(root.left); System.out.println(root.value); InOrder(root.right); } } public void postOrder(Node root){ if(root != null){ postOrder(root.left); postOrder(root.right); System.out.println(root.value); } } }