Let T be a binary tree with n nodes that is realized with an array list, S, and let p be the level numbering of the nodes in T. Give pseudo-code descriptions of each of the methods root, parent, left, right, hasleft, hasRight, islnternal, isExternal, and isRoot.
时间: 2024-01-16 07:05:29 浏览: 94
Assuming that the nodes in the array list S are stored in level order (i.e., the root is at index 0, its children at 1 and 2, their children at 3, 4, 5, and 6, and so on), the pseudo-code descriptions for each of the methods are as follows:
1. root: Return the node at index 0 in the array list S.
```
root(S):
return S[0]
```
2. parent: Return the parent of the node at index i in the array list S. If i is the root, return None.
```
parent(S, i):
if i == 0:
return None
else:
return S[(i-1)//2]
```
3. left: Return the left child of the node at index i in the array list S. If the node has no left child, return None.
```
left(S, i):
left_child = 2*i + 1
if left_child < len(S):
return S[left_child]
else:
return None
```
4. right: Return the right child of the node at index i in the array list S. If the node has no right child, return None.
```
right(S, i):
right_child = 2*i + 2
if right_child < len(S):
return S[right_child]
else:
return None
```
5. hasLeft: Return True if the node at index i in the array list S has a left child, and False otherwise.
```
hasLeft(S, i):
return (2*i + 1) < len(S)
```
6. hasRight: Return True if the node at index i in the array list S has a right child, and False otherwise.
```
hasRight(S, i):
return (2*i + 2) < len(S)
```
7. isInternal: Return True if the node at index i in the array list S has at least one child (i.e., it is not a leaf), and False otherwise.
```
isInternal(S, i):
return hasLeft(S, i) or hasRight(S, i)
```
8. isExternal: Return True if the node at index i in the array list S has no children (i.e., it is a leaf), and False otherwise.
```
isExternal(S, i):
return not isInternal(S, i)
```
9. isRoot: Return True if the node at index i in the array list S is the root of the tree, and False otherwise.
```
isRoot(S, i):
return i == 0
```
阅读全文