Lesson 81: Binary tree
עמוד זה דורש דפדפן עדכני (תומך ב-SharedArrayBuffer). אנא עדכן את Chrome, Edge, Firefox או Safari לגרסה העדכנית ביותר.
English
Left is earlier, right is later
- In a binary tree each node has up to two children: a left pointer and a right pointer. The first node is the root.
- In an ordered binary tree, everything in the left subtree comes before the node, and everything in the right subtree comes after it.
- In-order traversal, left, node, right, visits the data in order. The function calls itself for each subtree: recursion.
| Index | leftPtr | data | rightPtr |
|---|---|---|---|
| 0 | 1 | Red | 2 |
| 1 | 3 | Green | 4 |
| 2 | 6 | Yellow | -1 |
| 3 | -1 | Blue | -1 |
| 4 | 5 | Orange | -1 |
| 5 | -1 | Indigo | -1 |
| 6 | -1 | Violet | -1 |

- rootPtr = 0. Lessons 76 to 78 show the other array-based structures: linked list, stack and queue.
English
In the exam
- 9618/31/O/N/24 Q11: the ordered binary tree Red, Green, Yellow, Blue, Orange, Indigo, Violet. (a) Draw it as nodes with LeftPtr, Data and RightPtr, with –1 as the null pointer. (b) Put it in an array of records. Mark scheme: RootPtr 0; Red has pointers 1 and 2; Green 3 and 4; Yellow left 6; Orange left 5; Blue, Indigo and Violet have –1 for both; FreePtr 7. The table above is that answer.
רמת קושי 5/5 · 400 מטבעות + בונוס קטן בהשלמה הראשונה היום
This is the exam's ordered binary tree of colours, stored in arrays. Each node has a left pointer, data and a right pointer; -1 is null. Write inOrder as a recursive function: visit the left subtree, then the node, then the right subtree. The colours then come out in alphabetical order.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
Type a colour. Finish search: start at the root and print each colour you visit. If it is the target, print found. If the target is earlier in the alphabet, go left, else go right. At a null pointer the colour is not in the tree.
לחץ על הרץ כדי לראות את התוצא כאן.