[Algorithm] binary tree creation

Source: Internet
Author: User

"Chained storage Structure"
struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode (int x): Val (x), left (null), right (null) {}};
"Hierarchy Create two fork tree"

Create two fork Tree treenode* createtreebylevel (vector<char> num) {    int len = Num.size ();    if (len = = 0) {        return NULL;    } If    queue<treenode*> queue;    int index = 0;    Create root node    TreeNode *root = new TreeNode (num[index++]);    Into the queue    Queue.push (root);    TreeNode *p = NULL;    while (!queue.empty () && Index < len) {        //out queue        p = Queue.front ();        Queue.pop ();        Left node        if (Index < len && Num[index]! =-1) {            //If not empty create a node            TreeNode *leftnode = new TreeNode (num[ Index]);            P->left = Leftnode;            Queue.push (Leftnode);        }        index++;        Right node if        (Index < len && Num[index]! =-1) {            //If not empty create a node            TreeNode *rightnode = new TreeNode (num [index]);            P->right = Rightnode;            Queue.push (Rightnode);        }        index++;    }    while return root;}

-1 represents NULL


Create a two fork tree input as above:

15 11 20 8 14-1-1-1-1 13-1

"First order Create two fork tree"

Creates a two  -fork-Tree int createbtree (treenode*& T) {      int data,      in order sequence; Enter the value of the node in the binary tree in order, 1 means empty tree      cin>>data;      if (data = =-1) {          T = NULL;      }      else{          T = new TreeNode (data);          Constructs left subtree          createbtree (t->left);          Construct right subtree          createbtree (t->right);      }      return 0;  

-1 represents null


Create a two fork tree input as above:

15 11 8-1-1 14 13-1-1-1 20-1-1




[Algorithm] binary tree creation

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.