- Visit the root.
- Traverse the left subtree.
- Traverse the right subtree.
| Preorder |
Inorder is
- Traverse the left subtree.
- Visit root.
- Traverse the right subtree.
| Inorder |
In python, using recursive to travel around, code is:
def preorder(tl: 'TreeList') -> list:
return [] if tl is None else ([tl[0]] + preorder(tl[1]) + preorder(tl[2]))
def inorder(tl: 'TreeList') -> list:
return [] if tl is None else inorder(tl[1]) + [tl[0]] + inorder(tl[2]).
In the exercise 3, we are asked to return the tree according to the preorder list and inorder list given. Accroding to the characteristic of two Tree traversal, it can be known that the first element in preorder is the first root node. Use .find to find the index i for preorder[0] in inorder, inorder[0:i]is the left subclass and inorder[i+1:]is the right subclass. And then the second element in preorder will be another node ...(using recursion)until all the element has been structed.
没有评论:
发表评论