二叉搜索树 插入节点

package com.yuzhiyun;

import com.yuzhiyun.PreOrder.BinaryTreeNode;

public class DealBinarySearchTree {
    /**
     * 二叉树的树结点
     */
    public static class BinaryTreeNode {

        public BinaryTreeNode(int value) {
            this.value = value;
            this.left = null;
            this.right = null;
        }
        int value;
        BinaryTreeNode left;
        BinaryTreeNode right;
    }

    static void midOrder(BinaryTreeNode node) {
        if(null==node)
            return;
        midOrder(node.left);
        if(node!=null)
            System.out.print(node.value+" ");
        midOrder(node.right);
    }
    public static void main(String[] args) {
        //      10
        //     / \
        //    5  12
        //   /\
        //  4  7
        BinaryTreeNode root = new BinaryTreeNode(10);
        root.left = new BinaryTreeNode(5);
        root.left.left = new BinaryTreeNode(4);
        root.left.right = new BinaryTreeNode(7);
        root.right = new BinaryTreeNode(12);
        System.out.println("中序打印二叉搜索树(有排序效果)");
        midOrder(root);
        System.out.println();
        System.out.println("二叉搜索树插入数据");
        insertNode(6,root);
        System.out.println();
        System.out.println("插入数据之后中序打印二叉搜索树(有排序效果)");
        midOrder(root);

    }
    /**
     * 往二叉搜索树中插入一个节点
     * 可以得知,我们的插入节点最终会变成二叉树的叶子节点,不会影响二叉树的其他节点位置变化
     */
    private static BinaryTreeNode insertNode(int i, BinaryTreeNode root) {
        if(null==root) {
            return new BinaryTreeNode(i);
        }
        if(i<root.value)
            root.left=insertNode(i, root.left);
        if(i>root.value)
            root.right=insertNode(i, root.right);
        //此处很有可能写错,记得要return本身
        return root;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值