Set up a binary tree using the array method

Source: Internet
Author: User

Description: Create a binary tree using the array method

For example there is an array of int p[7] = {0, 1, 2, 3, 4, 5, 6}; So how do you build this array into a binary tree? Take a look at the following code.

/**************************************************************************** @file: main.cpp* @author: ugly_chen* @date: 2015.1.3* @remark: This code was for the binary tree with array* @note ************************************************* /#include <iostream>using namespace std;struct binary_tree_node{int data;binary_ tree_node* left_child;binary_tree_node* Right_child;}; void Create_tree (binary_tree_node* &tree, int a[], int len, int index) {if (index >= len) return;tree = new Binary_tr Ee_node;tree->data = A[index];tree->left_child = Null;tree->right_child = Null;create_tree (Tree->left_ Child, A, Len, 2 * index + 1); Create_tree (Tree->right_child, A, Len, 2 * index + 2);} void Print (binary_tree_node* p) {if (NULL = = p) return;cout << p->data; Print (P->left_child); Print (p->right_child);} int main () {int p[7] = {0, 1, 2, 3, 4, 5, 6};binary_tree_node*tree;create_tree (tree, p, 7, 0); Print (tree); return 0;}


Set up a binary tree using the array method

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.