📜  二叉树每一层的最大值 | Set-2(迭代方法)

📅  最后修改于: 2022-05-13 01:57:19.318000             🧑  作者: Mango

二叉树每一层的最大值 | Set-2(迭代方法)

给定一棵包含n 个节点的二叉树。问题是找到并打印每个级别中存在的最大值。
例子:

Input :
        1
       / \
      2   3 
Output : 1 3

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

方法:在上一篇文章中,已经讨论了一种递归方法。在这篇文章中,我们讨论了一种迭代方法。这个想法是使用队列执行二叉树的迭代级顺序遍历。遍历时保持最大变量,该变量存储正在处理的树的当前级别的最大元素。完全遍历关卡后,打印该最大值

C++
// C++ implementation to print largest
// value in each level of Binary Tree
#include 
 
using namespace std;
 
// structure of a node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
 
// function to get a new node
Node* newNode(int data)
{
    // allocate space
    Node* temp = new Node;
 
    // put in the data
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// function to print largest value
// in each level of Binary Tree
void largestValueInEachLevel(Node* root)
{
    // if tree is empty
    if (!root)
        return;
 
    queue q;
    int nc, max;
 
    // push root to the queue 'q'
    q.push(root);
 
    while (1) {
        // node count for the current level
        nc = q.size();
 
        // if true then all the nodes of
        // the tree have been traversed
        if (nc == 0)
            break;
 
        // maximum element for the current
        // level
        max = INT_MIN;
 
        while (nc--) {
 
            // get the front element from 'q'
            Node* front = q.front();
 
            // remove front element from 'q'
            q.pop();
 
            // if true, then update 'max'
            if (max < front->data)
                max = front->data;
 
            // if left child exists
            if (front->left)
                q.push(front->left);
 
            // if right child exists
            if (front->right)
                q.push(front->right);
        }
 
        // print maximum element of
        // current level
        cout << max << " ";
    }
}
 
// Driver code
int main()
{
    /* Construct a Binary Tree
        4
       / \
      9   2
     / \   \
    3   5   7 */
 
    Node* root = NULL;
    root = newNode(4);
    root->left = newNode(9);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(5);
    root->right->right = newNode(7);
 
    // Function call
    largestValueInEachLevel(root);
 
    return 0;
}


Java
// Java implementation to print largest
// value in each level of Binary Tree
import java.util.*;
class GfG {
 
    // structure of a node of binary tree
    static class Node
    {
        int data;
        Node left = null;
        Node right = null;
    }
 
    // function to get a new node
    static Node newNode(int val)
    {
        // allocate space
        Node temp = new Node();
 
        // put in the data
        temp.data = val;
        temp.left = null;
        temp.right = null;
        return temp;
    }
 
    // function to print largest value
    // in each level of Binary Tree
    static void largestValueInEachLevel(Node root)
    {
        // if tree is empty
        if (root == null)
            return;
 
        Queue q = new LinkedList();
        int nc, max;
 
        // push root to the queue 'q'
        q.add(root);
 
        while (true)
        {
            // node count for the current level
            nc = q.size();
 
            // if true then all the nodes of
            // the tree have been traversed
            if (nc == 0)
                break;
 
            // maximum element for the current
            // level
            max = Integer.MIN_VALUE;
 
            while (nc != 0)
            {
 
                // get the front element from 'q'
                Node front = q.peek();
 
                // remove front element from 'q'
                q.remove();
 
                // if true, then update 'max'
                if (max < front.data)
                    max = front.data;
 
                // if left child exists
                if (front.left != null)
                    q.add(front.left);
 
                // if right child exists
                if (front.right != null)
                    q.add(front.right);
                nc--;
            }
 
            // print maximum element of
            // current level
            System.out.println(max + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        /* Construct a Binary Tree
            4
        / \
        9 2
        / \ \
        3 5 7 */
 
        Node root = null;
        root = newNode(4);
        root.left = newNode(9);
        root.right = newNode(2);
        root.left.left = newNode(3);
        root.left.right = newNode(5);
        root.right.right = newNode(7);
 
        // Function call
        largestValueInEachLevel(root);
    }
}


Python3
# Python program to print largest value
# on each level of binary tree
 
INT_MIN = -2147483648
 
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
 
 
class newNode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to find largest values
 
 
def largestValueInEachLevel(root):
    if (not root):
        return
    q = []
    nc = 10
    max = 0
    q.append(root)
    while (1):
        # node count for the current level
        nc = len(q)
 
        # if true then all the nodes of
        # the tree have been traversed
        if (nc == 0):
            break
 
        # maximum element for the current
        # level
        max = INT_MIN
        while (nc):
 
            # get the front element from 'q'
            front = q[0]
 
            # remove front element from 'q'
            q = q[1:]
 
            # if true, then update 'max'
            if (max < front.data):
                max = front.data
 
            # if left child exists
            if (front.left):
                q.append(front.left)
 
            # if right child exists
            if (front.right != None):
                q.append(front.right)
            nc -= 1
 
        # print maximum element of
        # current level
        print(max, end=" ")
 
 
# Driver Code
if __name__ == '__main__':
    """ Let us construct the following Tree
        4
        / \
        9 2
    / \ \
    3 5 7 """
    root = newNode(4)
    root.left = newNode(9)
    root.right = newNode(2)
    root.left.left = newNode(3)
    root.left.right = newNode(5)
    root.right.right = newNode(7)
     
    # Function call
    largestValueInEachLevel(root)
 
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)


C#
// C# implementation to print largest
// value in each level of Binary Tree
using System;
using System.Collections.Generic;
 
class GfG
{
 
    // structure of a node of binary tree
    class Node
    {
        public int data;
        public Node left = null;
        public Node right = null;
    }
 
    // function to get a new node
    static Node newNode(int val)
    {
        // allocate space
        Node temp = new Node();
 
        // put in the data
        temp.data = val;
        temp.left = null;
        temp.right = null;
        return temp;
    }
 
    // function to print largest value
    // in each level of Binary Tree
    static void largestValueInEachLevel(Node root)
    {
        // if tree is empty
        if (root == null)
            return;
 
        Queue q = new Queue();
        int nc, max;
 
        // push root to the queue 'q'
        q.Enqueue(root);
 
        while (true)
        {
            // node count for the current level
            nc = q.Count;
 
            // if true then all the nodes of
            // the tree have been traversed
            if (nc == 0)
                break;
 
            // maximum element for the current
            // level
            max = int.MinValue;
 
            while (nc != 0)
            {
                // get the front element from 'q'
                Node front = q.Peek();
 
                // remove front element from 'q'
                q.Dequeue();
 
                // if true, then update 'max'
                if (max < front.data)
                    max = front.data;
 
                // if left child exists
                if (front.left != null)
                    q.Enqueue(front.left);
 
                // if right child exists
                if (front.right != null)
                    q.Enqueue(front.right);
                nc--;
            }
 
            // print maximum element of
            // current level
            Console.Write(max + " ");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        /* Construct a Binary Tree
            4
        / \
        9 2
        / \ \
        3 5 7 */
 
        Node root = null;
        root = newNode(4);
        root.left = newNode(9);
        root.right = newNode(2);
        root.left.left = newNode(3);
        root.left.right = newNode(5);
        root.right.right = newNode(7);
 
        // Function call
        largestValueInEachLevel(root);
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript



输出
4 9 7 

复杂性分析:

时间复杂度: O(N),其中 N 是树中节点的总数。

在级别顺序遍历中,树的每个节点都被处理一次,因此如果树中总共有 N 个节点,则级别顺序遍历的复杂度为 O(N)。此外,在处理每个节点时,我们会在每个级别保持最大元素,但这不会影响整体时间复杂度。因此,时间复杂度为 O(N)。

辅助空间: O(w),其中 w 是树的最大宽度。

在级别顺序遍历中,维护一个队列,其最大大小在任何时候都可以达到二叉树的最大宽度。