Essential Array Operations and Binary Tree Traversal

Array Traversal

Traversal means accessing or visiting each element of an array one by one. It is used to display, process, or perform operations on all elements of the array. Traversal is a fundamental operation in data structures.

Algorithm for Array Traversal

  1. Start
  2. Enter the size of array N
  3. Enter the array elements
  4. Set I = 0
  5. Repeat while I < N:
    • Print ARR[I]
    • Set I = I + 1
  6. Stop

Example: Suppose the array is A = [10, 20, 30, 40]. After traversal, the output will be: 10 20 30 40.

Pros and Cons

  • Advantages: Useful for displaying, searching, and processing data.
  • Disadvantages: Time-consuming for large arrays as every element must be checked.

Array Selection

Selection in an array involves finding a particular element to determine if it exists. The operation checks elements one by one until the required item is found.

Algorithm for Array Selection

  1. Start
  2. Enter the size of array N
  3. Enter array elements
  4. Enter the item to be searched
  5. Set I = 0
  6. Repeat while I < N:
    • If ARR[I] = ITEM, print “Element Found” and go to Step 8
    • Else, set I = I + 1
  7. Print “Element Not Found”
  8. Stop

Array Insertion

Insertion involves adding a new element at a specific position. Elements are shifted to create space for the new entry.

Algorithm for Insertion

  1. Start
  2. Enter the size of array N
  3. Enter array elements
  4. Enter the element ITEM to be inserted
  5. Enter the position POS
  6. Shift elements from N-1 to POS towards the right
  7. Insert ITEM at position POS
  8. Increase the size of array by 1
  9. Print the updated array
  10. Stop

Array Deletion

Deletion is the process of removing an element at a specific position. Remaining elements are shifted left to fill the gap.

Algorithm for Deletion

  1. Start
  2. Enter the size of array N
  3. Enter array elements
  4. Enter the position POS of the element to be deleted
  5. Repeat from I = POS to N-1:
    • ARR[I] = ARR[I + 1]
  6. Set N = N – 1
  7. Print updated array
  8. Stop

Binary Tree Traversal

Preorder Traversal Algorithm

  1. Initialize: TOP := 1, S[1] := NULL, PTR := ROOT
  2. Repeat Steps 3 to 5 while PTR ≠ NULL
  3. Apply PROCESS to INFO[PTR]
  4. Check right child: If RPTR[PTR] ≠ NULL, set TOP := TOP + 1 and S[TOP] := RPTR[PTR]
  5. Check left child: If LPTR[PTR] ≠ NULL, set PTR := LPTR[PTR]; else, pop from stack (PTR := S[TOP], TOP := TOP – 1)
  6. Exit

Inorder Traversal Algorithm

  1. Initialize: TOP := 1, S[1] := NULL, PTR := ROOT
  2. Push left-most path: Repeat while PTR ≠ NULL (Set TOP := TOP + 1, S[TOP] := PTR, PTR := LPTR[PTR])
  3. Pop nodes: Set PTR := S[TOP], TOP := TOP – 1
  4. Repeat steps 5 to 7 while PTR ≠ NULL
  5. Process node: Apply PROCESS to INFO[PTR]
  6. Check right node: If RPTR[PTR] ≠ NULL, set PTR := RPTR[PTR] and go to step 2
  7. Pop node: Set PTR := S[TOP], TOP := TOP – 1
  8. Exit