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.
実行ボタンをクリックして出力を確認してください。