This post is completed by 1 user
|
Add to List |
178. Search the Element in a binary tree - With and Without Recursion
Objective: Given a binary tree and a given number x, Write a recursive algorithm to search the element in the tree.
This is one of the very basic problems of trees. If you are new to binary trees, this problem might help you to understand the tree. First, we will see the recursive solution and then we will solve it without recursion.
Approach:
Recursive Approach:
The approach will be quite simple, do any of the tree traversals(inorder, preorder, postorder, BFS or DFS) and check if the given element is present.
Does 4 exist in the tree: true Does 7 exist in the tree: false
Non-Recursive Approach:
- If we are not using recursion then we need a data structure to store the tree traversal, we will use a queue here
- Add root to the queue
- Check if the current node has the element we are looking for if yes then return true else add children nodes of the current node to the queue
- If the queue gets empty, which means we have not found the element
Output:
Does 4 exist in the tree: true Does 7 exist in the tree: false