vault backup: 2024-03-21 22:58:58
This commit is contained in:
53
Semester 2/Programming 2/Week 10 Revision/Q5.md
Normal file
53
Semester 2/Programming 2/Week 10 Revision/Q5.md
Normal file
@@ -0,0 +1,53 @@
|
||||
a) List the order in which the nodes are visited in:
|
||||
post-order.
|
||||

|
||||
D,B,F,G,E,C,A
|
||||
|
||||
pre-order
|
||||
A,B,D,C,E,F,G
|
||||
|
||||
in-order
|
||||
D,B,F,E,G,C,A
|
||||
|
||||
b)
|
||||
```java
|
||||
public class BinTreeNode
|
||||
{
|
||||
public String info;
|
||||
public BinTreeNode leftChild, rightChild;
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public void postTraverse( BinTreeNode node )
|
||||
{
|
||||
if ( node != null )
|
||||
{
|
||||
postTraverse( node.leftNode );
|
||||
postTraverse( node.rightNode );
|
||||
System.out.println( node.info );
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
c) The following method counts the number of nodes in the tree
|
||||
```java
|
||||
public int countTree(BinTreeNode t)
|
||||
{
|
||||
int count;
|
||||
if (t == null)
|
||||
count = 0
|
||||
else
|
||||
count = countTree(t.leftChild)+countTree(t.rightChild)+1;
|
||||
return count;
|
||||
}
|
||||
```
|
||||

|
||||
|
||||
countTree(root)
|
||||
-> count = countTree(t.leftChild) + countTree(t.rightChild+1)
|
||||
countTree(t.leftChild)
|
||||
-> return 1, since left and right child null
|
||||
countTree(t.rightChild)
|
||||
-> return 1, since left and right child null
|
||||
count = 1 + 1 + 1 = 3
|
Reference in New Issue
Block a user