Convert an ordered array to a binary tree

Source: Internet
Author: User

This question is a bit ambiguous, just to convert it into a binary tree. This does not mean a balanced binary tree or a binary sorting tree.

If you can use an array as the output for any binary tree, you can use the pre-order, middle-order, or subsequent binary tree construction. There is a lot of code for building a binary tree on the Internet.

The following code is a binary sorting tree of resumes.

First, use the intermediate element of the array as the root to establish a binary tree, and then recursively return the left and right subtree of the resume.

# Include <iostream> # include <queue> # include <windows. h> using namespace STD; typedef struct node {int data; struct node * left; struct node * right;} node, * bitree; void buildtree (bitree & T, int A [], int begin, int end) // create a binary sorting tree {If (begin> end) // recursive exit return; int mid = (begin + end) /2; // subscript of the intermediate element if (t = NULL) // apply for space for the root node of the current tree {T = (node *) malloc (sizeof (node); t-> DATA = A [Mid]; // value assignment t-> left = NULL; // left and right subtree must also be set to null T-> righ T = NULL;} cout <A [Mid] <""; // The following two actions show the creation process sleep (1000); buildtree (t-> left, a, begin, mid-1); // recursive resume left subtree buildtree (t-> right, A, Mid + 1, end ); // recursively create the right subtree} void travel (bitree t) {If (T! = NULL) {travel (t-> left); cout <t-> data <""; // traverse travel (t-> right) in the middle order );}} int main () {int A [] = {1, 3, 4, 5, 6, 7, 8, 9}; bitree root = NULL; int begin = 0, end = 8; buildtree (root, a, begin, end); cout <Endl; travel (Root); getchar (); Return 0 ;}

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.