Java语言实现二叉树

来源:互联网 发布:java中如何使用debug 编辑:程序博客网 时间:2024/06/05 10:04

Java语言实现二叉树


代码

import java.util.Scanner;/** * Java语言实现的二叉树结构  * 原理分析 主要采用递归思想 *  * @author tuzhao * @github tuzhao * @mail tuzhaocn@gmail.com */public class BinaryTree {    public static class Node {        int item;        int count;        Node pLeft;        Node pRight;    }    public static void main(String[] args) {        int newValue = 0;        Node pRoot = null;        long answer = 0;        Scanner scanner = new Scanner(System.in);        do {            newValue = 0;            System.out.println("please enter the node value:   (-2147483648 -- 2147483647)");            newValue = scanner.nextInt();            if (pRoot == null) {                pRoot = createNode(newValue);            } else {                addNode(newValue, pRoot);            }            answer = 0;            System.out.println("do you want to enter another? 1 is yes! 0 is stop!");            answer = scanner.nextLong();        } while (answer == 1);        System.out.println("all the intput value is:");        listNodes(pRoot);        freeNodes(pRoot);        scanner.close();    }    public static Node createNode(int v) {        Node node = new Node();        node.item = v;        node.count = 1;        node.pLeft = null;        node.pRight = null;        return node;    }    public static Node addNode(int v, Node pNode) {        if (pNode == null) {            return createNode(v);        }        if (pNode.item == v) {            pNode.count++;            return pNode;        }        if (v < pNode.item) {            if (pNode.pLeft == null) {                pNode.pLeft = createNode(v);                return pNode.pLeft;            } else {                return addNode(v, pNode.pLeft);            }        } else {            if (pNode.pRight == null) {                pNode.pRight = createNode(v);                return pNode.pRight;            } else {                return addNode(v, pNode.pRight);            }        }    }    public static void listNodes(Node pNode) {        if (pNode.pLeft != null) {            listNodes(pNode.pLeft);        }        for (int i = 0; i < pNode.count; i++) {            System.out.println(pNode.item);        }        if (pNode.pRight != null) {            listNodes(pNode.pRight);        }    }    public static void freeNodes(Node pNode) {        if (pNode == null) {            return;        }        if (pNode.pLeft != null) {            freeNodes(pNode.pLeft);        }        if (pNode.pRight != null) {            freeNodes(pNode.pRight);        }        pNode = null;    }}
1 0
原创粉丝点击