• 使用Integer类实现二叉树排序


    class BinaryTree {
        class Node {
            private Comparable data;
            private Node left;
            private Node right;

            public void addNode(Node newNode) {
                if (newNode.data.compareTo(this.data) < 0) {
                    if (this.left == null) {
                        this.left = newNode;
                    } else {
                        this.left.addNode(newNode);
                    }
                }
                if (newNode.data.compareTo(this.data) >= 0) {
                    if (this.right == null) {
                        this.right = newNode;
                    } else {
                        this.right.addNode(newNode);
                    }
                }
            }

            public void printNode() {
                if (this.left != null) {
                    this.left.printNode();
                }
                System.out.print(this.data + " ");
                if (this.right != null) {
                    this.right.printNode();
                }
            }
        };

        private Node root;

        public void add(Comparable data) {
            Node newNode = new Node();
            newNode.data = data;
            if (root == null) {
                root = newNode;
            } else {
                root.addNode(newNode);
            }
        }

        public void print() {
            this.root.printNode();
        }
    }

    public class ComparebleDemo03 {
        public static void main(String[] args) {
            BinaryTree bt = new BinaryTree();
            bt.add(8);
            bt.add(3);
            bt.add(3);
            bt.add(10);
            bt.add(9);
            bt.add(1);
            bt.add(5);
            bt.add(5);
            System.out.println("After sorted:");
            bt.print();
        }
    }

  • 相关阅读:
    2019南京网络赛 D Robots 期望dp
    【ICPC2019银川站】K
    【ICPC2019南昌站】I
    【SEERC 2019】E
    电子取证知识和经验总结
    CCPC2020绵阳站游记
    【CCPC2020绵阳站】J
    【CCPC2020绵阳站】K
    【SWERC 2019-20】K Birdwatching
    【HAOI2012】容易题
  • 原文地址:https://www.cnblogs.com/vonk/p/3912526.html
Copyright © 2020-2023  润新知