VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-value-level-binary-tree-set-2-iterative-approach/

⇱ Largest value in each level of Binary Tree | Set-2 (Iterative Approach) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest value in each level of Binary Tree | Set-2 (Iterative Approach)

Last Updated : 2 Aug, 2022

Given a binary tree containing n nodes. The problem is to find and print the largest value present in each level.

Examples: 

Input :
 1
 / \
 2 3 
 
Output : 1 3

Input : 
 4
 / \
 9 2
 / \ \
 3 5 7 

Output : 4 9 7

Approach: In the previous post, a recursive method have been discussed. In this post an iterative method has been discussed. The idea is to perform iterative level order traversal of the binary tree using queue. While traversing keep max variable which stores the maximum element of the current level of the tree being processed. When the level is completely traversed, print that max value.  

Implementation:


Output
4 9 7 

  • Time Complexity: O(N) where N is the total number of nodes in the tree. 
    In level order traversal, every node of the tree is processed once and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Also, while processing every node, we are maintaining the maximum element at each level, however, this does not affect the overall time complexity. Therefore, the time complexity is O(N).
  • Auxiliary Space: O(w) where w is the maximum width of the tree.
    In level order traversal, a queue is maintained whose maximum size at any moment can go upto the maximum width of the binary tree.
Comment
Article Tags: