Generate balanced search by ordered array binary tree __ Search

Source: Internet
Author: User
Tags stringbuffer

Generate balanced search by ordered array binary tree public class generatebst{//two fork tree node definition public static class node{public int value;
       Public Node left;

       public Node right;
       public Node (int data) {this.value=data;
        	}///Generate balanced binary search tree public static Node Generatebstree (Int[]arr) {if (arr==null) {
        return null;

    return generate (ARR,0,ARR.LENGTH-1);
       	 ///recursive Generation two fork sort tree public static Node generate (Int[]arr,int Start,int end) {if (start>end) {
       return null;
       int mid= (start+end)/2;
       Node Head=new node (Arr[mid]);//Generating head nodes head.left=generate (arr,start,mid-1);
       Head.right=generate (Arr,mid+1,end);

    return head;
    //***************************************************//visual print binary tree public static void Printtree (Node head) {
    System.out.println ("Binary tree:");
    Printinorder (head, 0, "H", 17);
  System.out.println (); } PublIC static void Printinorder (Node head, int height, String to, int len) {if (head = = null) {return;
    Printinorder (head.right, height + 1, "V", Len);
    String val = to + Head.value + to;
    int lenm = Val.length ();
    int lenl = (LEN-LENM)/2;
    int lenr = LEN-LENM-LENL;
    val = Getspace (lenl) + val + getspace (lenr);
    System.out.println (getspace (height * len) + val);
  Printinorder (head.left, height + 1, "^", Len);
    public static string getspace (int num) {String space = ' ";
    StringBuffer buf = new StringBuffer ("");
    for (int i = 0; i < Num. i++) {buf.append (space);
  return buf.tostring ();
       //************************************************ public static void Main (String[]args) {int[]arr={1,2,3,4};
       Node Head=generatebstree (arr);
	Printtree (head); }

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.