ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Find Maximum Element in Binary Tree

Swift

Goal -- WPM

Ready
Exercise Algorithm Area
1class TreeNode {
2var val: Int
3var left: TreeNode?
4var right: TreeNode?
5
6init(_ val: Int) {
7self.val = val
8self.left = nil
9self.right = nil
10}
11}
12
13func findMaximumInBinaryTree(root: TreeNode?) -> Int? {
14// Handle the edge case of an empty tree.
15guard let rootNode = root else {
16return nil
17}
18
19// Initialize maximum value with the root's value.
20var maxValue = rootNode.val
21
22// Recursively find the maximum in the left subtree.
23if let leftMax = findMaximumInBinaryTree(root: rootNode.left) {
24maxValue = max(maxValue, leftMax)
25}
26
27// Recursively find the maximum in the right subtree.
28if let rightMax = findMaximumInBinaryTree(root: rootNode.right) {
29maxValue = max(maxValue, rightMax)
30}
31
32return maxValue
33}
34
35// Helper function to demonstrate finding the maximum.
36func demonstrateMaxInTree() {
37// Example 1: A balanced tree.
38let root1 = TreeNode(10)
39root1.left = TreeNode(5)
40root1.right = TreeNode(15)
41root1.left?.left = TreeNode(2)
42root1.left?.right = TreeNode(7)
43root1.right?.left = TreeNode(12)
44root1.right?.right = TreeNode(20)
45
46if let maxVal = findMaximumInBinaryTree(root: root1) {
47print("Maximum value in tree 1: \(maxVal)") // Expected: 20
48} else {
49print("Tree 1 is empty.")
50}
51
52// Example 2: A tree with only one node.
53let root2 = TreeNode(50)
54if let maxVal = findMaximumInBinaryTree(root: root2) {
55print("Maximum value in tree 2: \(maxVal)") // Expected: 50
56} else {
57print("Tree 2 is empty.")
58}
59
60// Example 3: An empty tree.
61let root3: TreeNode? = nil
62if let maxVal = findMaximumInBinaryTree(root: root3) {
63print("Maximum value in tree 3: \(maxVal)")
64} else {
65print("Tree 3 is empty.") // Expected: Tree 3 is empty.
66}
67}
68
69demonstrateMaxInTree()
Algorithm description viewbox

Find Maximum Element in Binary Tree

Algorithm description:

This function finds the largest integer value stored within a binary tree. It traverses the tree, comparing node values to keep track of the maximum encountered so far. This is a common operation for analyzing tree data structures.

Algorithm explanation:

The `findMaximumInBinaryTree` function finds the maximum value in a binary tree using recursion. It first handles the base case: if the `root` is `nil` (an empty tree), it returns `nil`. Otherwise, it initializes `maxValue` with the value of the current `rootNode`. It then recursively calls itself on the left child (`rootNode.left`). If the recursive call returns a non-nil value (meaning the left subtree is not empty), it updates `maxValue` to be the greater of the current `maxValue` and the maximum from the left subtree. The same process is repeated for the right child (`rootNode.right`). This ensures that `maxValue` always holds the largest value found in the current node and its subtrees. The time complexity is O(n), where n is the number of nodes in the tree, because each node is visited exactly once. The space complexity is O(h) in the average case (for a balanced tree) and O(n) in the worst case (for a skewed tree), due to the recursion stack depth, where h is the height of the tree. This recursive approach correctly identifies the maximum value by systematically exploring all nodes.

Pseudocode:

function findMaximumInBinaryTree(root):
  if root is null:
    return null

  maxValue = root.value

  leftMax = findMaximumInBinaryTree(root.left)
  if leftMax is not null:
    maxValue = max(maxValue, leftMax)

  rightMax = findMaximumInBinaryTree(root.right)
  if rightMax is not null:
    maxValue = max(maxValue, rightMax)

  return maxValue