java复习之二叉树前序,中序,后续遍历

二叉树前序,中序,后续遍历

package learn.tree;

import sun.reflect.generics.tree.Tree;

public class TreeDemo {
    public static void main(String[] args) {
        Tree1 tree1 = new Tree1();
        TreeNode treeNode1 = new TreeNode(1,"李1");
        TreeNode treeNode2 = new TreeNode(2,"李2");
        TreeNode treeNode3 = new TreeNode(3,"李3");
        TreeNode treeNode4 = new TreeNode(4,"李4");
        TreeNode treeNode5 = new TreeNode(5,"李5");
        TreeNode treeNode6 = new TreeNode(6,"李6");
        TreeNode treeNode7 = new TreeNode(7,"李7");
        tree1.root = treeNode1;
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode3.right=treeNode4;
        treeNode4.left=treeNode5;
        treeNode4.right=treeNode6;
        treeNode6.right=treeNode7;
        tree1.pre(treeNode1);
        System.out.println("==============");
        tree1.mid(treeNode1);
        System.out.println("************");
        tree1.end(treeNode1);

    }
}

class Tree1{
    public TreeNode root;

    public Tree1() {
    }

    public Tree1(TreeNode root) {
        this.root=root;
    }

    public TreeNode getRoot() {
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public void pre(TreeNode root){
        System.out.println(root);
        if(root.left!=null){
            pre(root.left);
        }
        if(root.right!=null){
            pre(root.right);
        }
    }
    public void mid(TreeNode root){

        if(root.left!=null){
            pre(root.left);
        }
        System.out.println(root);
        if(root.right!=null){
            pre(root.right);
        }
    }
    public void end(TreeNode root){

        if(root.left!=null){
            pre(root.left);
        }
        if(root.right!=null){
            pre(root.right);
        }
        System.out.println(root);
    }
}
class TreeNode{
    private int id;
    private String name;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

}

你可能感兴趣的:(数据结构,笔记,java复习,二叉树)