把一个有序整数数组放到二叉树中

本文介绍了一种将有序数组转换为二叉搜索树的方法。通过递归地选取数组中间元素作为根节点,可以有效地将数组划分为左右子树,并最终构建出一棵平衡的二叉搜索树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为数组是有序,数组的中间节点就是根节点,这样数组就可以分为2个部分,左子树和右子树

分析:本题考察二叉搜索树的建树方法,简单的递归结构。关于树的算法设计一定要联想到递归,因为树本身就是递归的定义。而,学会把递归改称非递归也是一种必要的技术。毕竟,递归会造成栈溢出,关于系统底层的程序中不到非不得以最好不要用。但是对某些数学问题,就一定要学会用递归去解决。



/**
 * Created by renshuang on 10/14/13.
 */
public class TestConverTree {


    public static void main(String args[]){

        int[] array={1,2,3,4,5};
        TestConverTree tree=new TestConverTree();
        tree.printMid(tree.arrayConvertBst(array,0,array.length-1));

    }


    public void printMid(Node node){
        if(node.left!=null){
            printMid(node.left);
        }
        System.out.println(node.data);
        if(node.right!=null){
            printMid(node.right);
        }
    }

    public  Node arrayConvertBst(int[] data,int start,int end){
              if(start>end){
                  return null;
              }

           int mid=(start+end)/2;
        Node current=new Node(data[mid]);
        current.left=arrayConvertBst(data,start,mid-1);
        current.right=arrayConvertBst(data,mid+1,end);
        return current;

    }

    class Node {
        int data;
        Node left;
        Node right;
        public Node(){

        }
        public Node(int data){
            this.data=data;
        }
        public Node(int data,Node left,Node right){
            this.data=data;
            this.left=left;
            this.right=right;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值