Introduction to the algorithm 10.4 a representation of a root tree

Source: Internet
Author: User

10.4-2 a two-fork tree given n nodes, writes out a recursive program of O (n) time, outputting the keywords for each node of the tree.

Pseudo code:

1 tree-print (T)2if T! = NIL3    PRINT key[t]4      tree-PRINT (left[t])5     tree-print (Right[t])

C Implementation:

void Treeprint (Tree t) {    if (t! = NULL)    {        printelement (t);        Treeprint (T-left);        Treeprint (T-right);    }}

10.4-3

(version one) pseudo-code:

1 tree-PRINT (T, S)2 while    t! = Nil or S! = Nil3       if T! = NIL4          PUSH (S, T)5          VISIT (t)6           T = t->left7       Else 8           t = POP (S)9           t = t->right

(version II) pseudo-code:

1tree-PRINT (T, S)2   ifT! =NIL3 PUSH (T, S)4        whileS! =NIL5Node =POP (S)6 VISIT (Node)7           ifLeft[node]! =NIL8 PUSH (Left[node], S)9           ifRight[node]! =NILTenPUSH (Right[node], S)

10.4-4

Analysis: The root tree is stored in a two-tree form and can be processed using the above method

10.4-5

Analysis: Adds a flag to the node and a pointer to the parent, which is the storage space of the tree itself, which uses a fixed amount of additional storage space

Pseudo code:

1 treeprint (T)2    whileT! =NIL3        whileLEFT[T]! = NIL and left[t]. Visited! =true4T =Left[t]5       ift.visited =false6 VISIT (T)7t.visited =true8       ifRIGHT[T]! = NIL and right[t]. Visited! =true9T =Right[t]Ten       Else OneT = Parent[t]

10.4-6

Solution: For a root tree, using binary tree storage, each node contains a left and right pointers and a bool value;

Set each node in the root tree, and if it has a child, set its last child's pointer to its father, which is the node, and set bool to true;

If there is a root tree node, the child's right pointer points to the sibling node, set the bool value to false;

Introduction to the algorithm 10.4 a representation of a root 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.