二叉排序树,新增节点,前序遍历,中序遍历,后续遍历

package com.xbb.demo.exam;

/**
 * 该类为按原始要求写的,未添加任何原始框架以外的方法;
 * 因要求二要求中序遍历按从小到大排序,所以按左子列为小,右子列为大新增节点.
 */
public class BinaryTree {

    public static void main(String[] args) {

        final int[] values = { 1, 3, 4, 5, 2, 8, 6, 7, 9, 0 };
        // TODO:
        Node node = null;
        for (int value:values) {
            node = createBinaryTree(node,value);
        }
        inOrderTransval(node);
    }

    /**
     * 原始要求:通过一个方法
     * 比较新加的值与原节点的大小;
     * 如果原节点值大于等于新增节点,返回True(代表放入左)
     * 如果原节点值小于新增节点,返回False(代表放入右)
     * @param node
     * @param value
     * @return
     */
    public static Node createBinaryTree(Node node,int value){
        // TODO:
        // 如果节点为空,代表为根节点,创建根节点写入当前值并返回
        if (node == null){
            return new Node(value);
        }else{
            // 根据左右写入规则,判断新增节点Value与当前节点Value的大小,从而判断写入左列还是右列
            // 新节点值<=当前节点 写入左列
            if (node.getValue() >= value){
                // 判断当前节点下是否为为空,
                // 如果不为空则递归进入当前方法寻找下一个节点
                if (node.getLeft() != null){
                    createBinaryTree(node.getLeft(),value);
                // 如果为空则创建节点写入新值
                }else{
                    node.setLeft(new Node(value));
                }
            // 否则,写入右列
            }else{
                // 判断当前节点下是否为为空,
                // 如果不为空则递归进入当前方法寻找下一个节点
                if (node.getRight() != null){
                    createBinaryTree(node.getRight(),value);
                }else{
                    // 如果为空则创建节点写入新值
                    node.setRight(new Node(value));
                }
            }
            return node;
        }
    }

    /**
     * 中序排序输出
     * @param node
     */
    public static void inOrderTransval(Node node) {
        // TODO:
        // 结束递归条件:节点为空
        if (node == null) return ;
        // 如果当前节点左节点不为空,递归排序左子
        if (node.getLeft() != null){
            inOrderTransval(node.getLeft());
        }
        System.out.print(node.getValue()+",");
        // 如果当前节点右节点不为空,递归排序右子
        if (node.getRight() != null){
            inOrderTransval(node.getRight());
        }
    }
}
class Node {

    // 节点值
    private int value;

    // 左节点
    private Node left;

    // 右节点
    private Node right;

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

    // TODO:
    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeft() {
        return left;
    }

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

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章