3. Advance
1. Tree using pair data structure
In Scheme, you can use pairs to build tree structures by defining each node in the tree as a pair. Here’s a basic approach to creating and manipulating binary trees using pairs:
1.1 Building a Binary Tree
A binary tree node can be represented as a pair where:
- The
carpart holds the value of the node. - The
cdrpart is itself a pair, where thecarof this second pair is the left subtree and thecdris the right subtree.
Here’s how you might define a simple binary tree:
(define (make-node value left right) (cons value (cons left right)))In this definition:
valueis the value of the current node.leftis the left subtree (can be another node or()if there is no left child).rightis the right subtree (can be another node or()if there is no right child).
1.2 Example Tree
Consider a tree with the following structure:
1 / \ 2 3 / \ 4 5You can represent this tree as follows:
(define tree (make-node 1 (make-node 2 (make-node 4 '() '()) (make-node 5 '() '())) (make-node 3 '() '())))1.3 Accessing Tree Elements
To access parts of the tree, you can use the car and cdr procedures:
carof the tree gives the root value.cdrgives a pair where:caris the left subtree.cdris the right subtree.
For example:
(define (root-value tree) (car tree))
(define (left-subtree tree) (car (cdr tree)))
(define (right-subtree tree) (cdr (cdr tree)))1.4 Traversing the Tree
You can write recursive functions to traverse the tree. Here’s an example of an in-order traversal:
(define (in-order-traversal tree) (if (null? tree) '() (append (in-order-traversal (left-subtree tree)) (list (root-value tree)) (in-order-traversal (right-subtree tree)))))