Given a binary tree and a target number x, write a recursive algorithm to determine if the number exists within the binary tree. If the target number exists in the tree, return True; otherwise, return False.
The problem can be approached using Depth First Search (DFS). When searching for x in a binary tree, we recursively explore the left and right subtrees until:
We find the target x and return True.
We reach a leaf node (null/None) and return False.
classSolution:
defisPresent(self, root, x):
# Base case: if the node is None, return Falseifnot root:
returnFalse# If the current node matches the value, return Trueif root.val == x:
returnTrue# Recursively check left and right subtrees left_search = self.isPresent(root.left, x)
right_search = self.isPresent(root.right, x)
# Combine the results of left and right subtreesreturn left_search or right_search
# Example usageif __name__ =="__main__":
# Construct binary tree root = Solution.TreeNode(8)
root.left = Solution.TreeNode(3)
root.right = Solution.TreeNode(10)
root.left.left = Solution.TreeNode(1)
root.left.right = Solution.TreeNode(6)
root.right.right = Solution.TreeNode(14)
sol = Solution()
print(sol.isPresent(root, 6)) # Output: True print(sol.isPresent(root, 7)) # Output: False
classSolution {
publicbooleanisPresent(TreeNode root, int x) {
// Base case: if the root is null, the value cannot be presentif (root ==null) {
returnfalse;
}
// Create a queue for BFS Queue<TreeNode> queue =new LinkedList<>();
queue.offer(root); // Add root to the queuewhile (!queue.isEmpty()) {
// Retrieve and remove the front node from the queue TreeNode current = queue.poll();
// Check if the current node's value matches the targetif (current.val== x) {
returntrue;
}
// Add the left child to the queue if it existsif (current.left!=null) {
queue.offer(current.left);
}
// Add the right child to the queue if it existsif (current.right!=null) {
queue.offer(current.right);
}
}
// If we exhaust the tree without finding x, return falsereturnfalse;
}
// Example usagepublicstaticvoidmain(String[] args) {
TreeNode root =new TreeNode(8);
root.left=new TreeNode(3);
root.right=new TreeNode(10);
root.left.left=new TreeNode(1);
root.left.right=new TreeNode(6);
root.right.right=new TreeNode(14);
Solution sol =new Solution();
System.out.println(sol.isPresent(root, 6)); // Output: true System.out.println(sol.isPresent(root, 7)); // Output: false }
}
classSolution:
defisPresent(self, root, x):
# Base case: if the root is None, return Falseifnot root:
returnFalse# Create a queue for BFS queue = deque([root]) # Initialize the queue with the root nodewhile queue:
# Retrieve and remove the front node from the queue current = queue.popleft()
# Check if the current node's value matches the targetif current.val == x:
returnTrue# Add the left child to the queue if it existsif current.left:
queue.append(current.left)
# Add the right child to the queue if it existsif current.right:
queue.append(current.right)
# If we exhaust the tree without finding x, return FalsereturnFalse# Example usageif __name__ =="__main__":
# Construct binary tree root = Solution.TreeNode(8)
root.left = Solution.TreeNode(3)
root.right = Solution.TreeNode(10)
root.left.left = Solution.TreeNode(1)
root.left.right = Solution.TreeNode(6)
root.right.right = Solution.TreeNode(14)
sol = Solution()
print(sol.isPresent(root, 6)) # Output: True print(sol.isPresent(root, 7)) # Output: False
⏰ Time complexity: O(n), as each node in the binary tree is visited once during the recursive traversal.
🧺 Space complexity: O(w) as maximum space required for the queue is proportional to the maximum number of nodes at any single level of the binary tree, where W is the tree’s width.