Preorder traversal algorithem added under /algorithms/tree

This commit is contained in:
RaviSadam 2024-07-03 15:19:46 +00:00
parent ac69359db2
commit a422bc6fff
3 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,31 @@
# Preorder Traversal Algorithm
Preorder traversal is an algorithm for traversing tree data structures.The algorithm involves visiting each node in a specific order: root node, left branch, and then the right branch.
## Preorder Traversal Steps
1. **Start at the root node** of the tree.
2. **Visit the root node**:
- Process the current node (e.g., print its value, apply a callback function).
3. **Recursively explore the left subtree**:
- Move to the left child of the current node.
- Repeat the preorder traversal on the left subtree.
4. **Recursively explore the right subtree**:
- Move to the right child of the current node.
- Repeat the preorder traversal on the right subtree.
## Complexities
### Time Complexity
O(N) Where N is number of nodes in Tree
### Space Complexity
O(H) Where H is height of tree
## References
- [Wikipedia](https://en.wikipedia.org/wiki/Tree_traversal)

View File

@ -0,0 +1,33 @@
import BinarySearchTreeNode from '../../../../data-structures/tree/binary-search-tree/BinarySearchTreeNode';
import preorderTraversal from '../preorderTraversal';
describe('Inorder Traversal of Binary tree', () => {
it('sholud give inorder travsersal of binary tree', () => {
// creating BST
const bst = new BinarySearchTreeNode(10);
// inserting values to BST
bst.insert(25);
bst.insert(-5);
bst.insert(11);
bst.insert(9);
bst.insert(8);
bst.insert(15);
// callback function
const callback = jest.fn();
preorderTraversal(bst, callback);
// checking number of times function called
expect(callback).toHaveBeenCalledTimes(7);
// checking values
expect(callback.mock.calls[0][0].value).toEqual(10);
expect(callback.mock.calls[1][0].value).toEqual(-5);
expect(callback.mock.calls[2][0].value).toEqual(9);
expect(callback.mock.calls[3][0].value).toEqual(8);
expect(callback.mock.calls[4][0].value).toEqual(25);
expect(callback.mock.calls[5][0].value).toEqual(11);
expect(callback.mock.calls[6][0].value).toEqual(15);
});
});

View File

@ -0,0 +1,25 @@
function preorderTraversalRecursive(root, callback) {
if (!root) {
return;
}
// callback calling
callback(root);
// left branch
preorderTraversalRecursive(root.left, callback);
// right branch
preorderTraversalRecursive(root.right, callback);
}
/**
* --preorder traversal of binary tree
* @param {BinaryTreeNode} root - Root node of binary tree
* @param {CallableFunction} callback
* - Callback function which calles for each node in preorder traversal
* @returns {void}
*/
export default function preorderTraversal(root, callback) {
preorderTraversalRecursive(root, callback);
}