1. 程式人生 > >二叉排序樹,java實現(知識簡單的實現,持續完善更新)

二叉排序樹,java實現(知識簡單的實現,持續完善更新)

定義:

二叉排序樹就是左子樹都比節點小,右子樹都比節點大。簡單的排序二叉樹實現。
程式碼:

package com.wzq.data_structure;

public class BinarySortTree {
    public Node root;

    public BinarySortTree(Node node) {
        this.root = node;
    }

    public BinarySortTree(int value) {
        Node node = new Node(value);
        this.root = node;
    }

    //排序二叉樹新增資料
public Node addNode(Node node, int value) { if (node == null) { node = new Node(value); return node; } else { if (value < node.value) { node.left = addNode(node.left, value); } else { node.right = addNode(node.right, value
); } return node; } } //中序遍歷 public void sortNode(Node sortNode) { Node node = sortNode; if (node == null) { return; } sortNode(node.left); println(node.value); sortNode(node.right); } private
void println(int value) { System.out.println(value); } //節點資料結構 private class Node { public int value; public Node left; public Node right; public Node(int value) { this.value = value; left = null; right = null; } } public static void main(String... str) { BinarySortTree bTree = new BinarySortTree(10); bTree.root = bTree.addNode(bTree.root, 5); bTree.root = bTree.addNode(bTree.root, 20); bTree.root = bTree.addNode(bTree.root, 3); bTree.root = bTree.addNode(bTree.root, 8); bTree.root = bTree.addNode(bTree.root, 15); bTree.root = bTree.addNode(bTree.root, 25); bTree.sortNode(bTree.root); } }