Java二叉树的插入和前中后序遍历

public class BinaryTree {
    private static TreeNode root;

    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.insert(2);
        binaryTree.insert(1);
        binaryTree.insert(3);
        binaryTree.preOrder(root);
        System.out.println();
        binaryTree.inOrder(root);
        System.out.println();
        binaryTree.postOrder(root);
    }

    public void insert(int value) {
        if (root == null) {
            root = new TreeNode(value);
            return;
        }
        TreeNode cur = root; //当前遍历到的节点
        TreeNode parent = root; //遍历到的节点的父节点
        boolean isLeft = true; //是否添加到左侧
        while (cur != null) {
            parent = cur;
            if (value < cur.value) {
                isLeft = true;
                cur = cur.left;
            } else {
                isLeft = false;
                cur = cur.right;
            }
        }
        TreeNode treeNode = new TreeNode(value);
        if (isLeft) {
            parent.left = treeNode;
        } else {
            parent.right = treeNode;
        }
    }

    public void preOrder(TreeNode treeNode) {//先序:根左右
        if (treeNode != null) {
            System.out.print(treeNode.value + " ");
            preOrder(treeNode.left);
            preOrder(treeNode.right);
        }
    }

    public void inOrder(TreeNode treeNode) {//中序:左根右
        if (treeNode != null) {
            inOrder(treeNode.left);
            System.out.print(treeNode.value + " ");
            inOrder(treeNode.right);
        }
    }

    public void postOrder(TreeNode treeNode) {//后序:左右根
        if (treeNode != null) {
            postOrder(treeNode.left);
            postOrder(treeNode.right);
            System.out.print(treeNode.value + " ");
        }
    }

    public static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }
    }
}

测试:

public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.insert(2);
        binaryTree.insert(1);
        binaryTree.insert(3);
        binaryTree.preOrder(root);
        System.out.println();
        binaryTree.inOrder(root);
        System.out.println();
        binaryTree.postOrder(root);
    }

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值