Example: 1 / \ 2 3 / \ / \ 4 5 6 7 N=1 => true N=10 => false
Queue
to traverse through the tree and check all the nodes
.
1. If root
is null
, return false
.
2. Create a Queue
to store the tree's nodes.
3. Add the root
node to the Queue
.
4. Start a loop
which runs till the Queue
becomes empty.
5. Remove a node from the Queue
and match its data with the data that needs to be found. If a match is found, return true.
6. Add the left
and right
nodes of this node to the Queue
.
7. At the end of the loop, return false
.
public boolean elemExist(TreeNode root, int data) { }
C
Java
Python