Sequence traversal of binary tree

Source: Internet
Author: User

Binary tree sequence traversal is from the top down, from the left and right to access each node, but in order to do so, the adjacent access to the two nodes are mostly not directly linked, difficult to access, so it will appear more troublesome, but we have a queue this good thing, build a sequential table queue, the address of each node in order to deposit, This is followed by sequential access in the queue. The key is whether the queue can exactly store each node in order from top to bottom, from left to right. Consider the following analysis.

local Indicates the position of the node currently being accessed in the queue, and length indicates the queue size. Local=0 when accessing a, you can add B, c to the queue, length=3; When Local=1 accesses B, it is possible to place D and E in the tail of the team, and the order of elements in the queue conforms to "sequence", and so on. It is clear that the length maximum will be a total of two fork tree elements, local=length when the last element is finally scanned, ending the loop at this point. The implementation code is as follows:

1 #defineSize_of_queue 2562 //Lchild point to left dial hand tree3 //Rchild refers to the right sub-tree4typedefstructbtree{5     intdata;6     structBTree *Lchild;7     structBTree *Rchild;8 }BT;9 Ten voiddisplaybylevel (BT root) { One BT Queue[size_of_queue]; A     intLocal; -     intlength; -queue[0] =Root; theLocal =0; -Length =1; -      while(Local <length) { -printf"%d\n", queue[local]->data); +         if(Queue[local]->lchild! =NULL) -queue[length++] = queue[local]->Lchild; +         if(Queue[local]->rchild! =NULL) Aqueue[length++] = queue[local]->Rchild; atlocal++; -     } -}

Sequence traversal of binary tree

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.