📌  相关文章
📜  在由值1组成的节点组成的二叉树中计数级别

📅  最后修改于: 2021-04-23 07:14:36             🧑  作者: Mango

给定仅由0 s和1 s组成的二叉树,任务是打印二叉树中所有1 s连续放置在一个组中的级别数。

例子:

方法:按照以下步骤解决问题:

  • 使用队列执行级别订单遍历。
  • 遍历二叉树的每个级别,并考虑以下三个变量:
    1. FLAG1:设置为1节点的第一次出现的与值1之后。
    2. flag0:在出现第一个值为1的节点后,第一次出现值为0的节点后,将其设置为1。
    3. flag2:在将flag0flag1都设置为1之后,第一次出现值为1的节点后进行设置。
  • 遍历每个级别后,检查flag1是否设置为1且flag2是否为0。如果确定为true,则将该级别包括在计数中。
  • 最后,打印获得的计数。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// A Binary Tree Node
struct node {
 
    // Left Child
    struct node* left;
 
    int data;
 
    // Right Child
    struct node* right;
};
 
// Function to perform level order traversal
// count levels with all 1s grouped together
int countLevels(node* root)
{
    if (root == NULL)
        return 0;
 
    int Count = 0;
 
    // Create an empty queue for
    // level order traversal
    queue q;
 
    // Stores front element of the queue
    node* curr;
 
    // Enqueue root and NULL node
    q.push(root);
 
    // Stores Nodes of
    // Current Level
    while (!q.empty()) {
        int n = q.size();
 
        int flag0 = 0, flag1 = 0, flag2 = 0;
 
        while (n--) {
 
            // Stores first node of
            // the current level
            curr = q.front();
            q.pop();
 
            if (curr) {
 
                // If left child exists
                if (curr->left)
 
                    // Push into the Queue
                    q.push(curr->left);
 
                // If right child exists
                if (curr->right)
 
                    // Push into the Queue
                    q.push(curr->right);
 
                if (curr->data == 1) {
 
                    // If current node is the first
                    // node with value 1
                    if (!flag1)
                        flag1 = 1;
 
                    // If current node has value 1
                    // after occurrence of nodes
                    // with value 0 following a
                    // sequence of nodes with value 1
                    if (flag1 && flag0)
                        flag2 = 1;
                }
 
                // If current node is the first node
                // with value 0 after a sequence
                // of nodes with value 1
                if (curr->data == 0 && flag1)
                    flag0 = 1;
            }
        }
 
        if (flag1 && !flag2)
            Count++;
    }
 
    return Count;
}
 
// Function to create a Tree Node
node* newNode(int data)
{
    node* temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Driver Code
int main()
{
    node* root = newNode(0);
    root->left = newNode(0);
    root->right = newNode(1);
    root->left->left = newNode(0);
    root->left->right = newNode(1);
    root->right->left = newNode(1);
    root->right->right = newNode(0);
 
    cout << countLevels(root);
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG
{
 
// A Binary Tree Node
static class node
{
 
    // Left Child
    node left;
    int data;
 
    // Right Child
    node right;
};
 
// Function to perform level order traversal
// count levels with all 1s grouped together
static int countLevels(node root)
{
    if (root == null)
        return 0;
    int Count = 0;
 
    // Create an empty queue for
    // level order traversal
    Queue q = new LinkedList<>();
 
    // Stores front element of the queue
    node curr;
 
    // Enqueue root and null node
    q.add(root);
 
    // Stores Nodes of
    // Current Level
    while (!q.isEmpty())
    {
        int n = q.size();
        int flag0 = 0, flag1 = 0, flag2 = 0;
        while (n-- >0)
        {
 
            // Stores first node of
            // the current level
            curr = q.peek();
            q.remove();
            if (curr != null)
            {
 
                // If left child exists
                if (curr.left != null)
 
                    // Push into the Queue
                    q.add(curr.left);
 
                // If right child exists
                if (curr.right != null)
 
                    // Push into the Queue
                    q.add(curr.right);
 
                if (curr.data == 1)
                {
 
                    // If current node is the first
                    // node with value 1
                    if (flag1 == 0)
                        flag1 = 1;
 
                    // If current node has value 1
                    // after occurrence of nodes
                    // with value 0 following a
                    // sequence of nodes with value 1
                    if (flag1 > 0 && flag0 > 0)
                        flag2 = 1;
                }
 
                // If current node is the first node
                // with value 0 after a sequence
                // of nodes with value 1
                if (curr.data == 0 && flag1 > 0)
                    flag0 = 1;
            }
        }
 
        if (flag1 > 0 && flag2 == 0)
            Count++;
    }
    return Count;
}
 
// Function to create a Tree Node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver Code
public static void main(String[] args)
{
    node root = newNode(0);
    root.left = newNode(0);
    root.right = newNode(1);
    root.left.left = newNode(0);
    root.left.right = newNode(1);
    root.right.left = newNode(1);
    root.right.right = newNode(0);
    System.out.print(countLevels(root));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
from collections import deque
 
# A Binary Tree Node
class node:
     
    def __init__(self):
         
        # Left Child
        self.left = None
 
        self.data = 0
 
        # Right Child
        self.right = None
 
# Function to perform level order traversal
# count levels with all 1s grouped together
def countLevels(root):
 
    if (root == None):
        return 0
 
    Count = 0
 
    # Create an empty queue for
    # level order traversal
    q = deque()
 
    # Stores front element of the queue
    curr = node()
 
    # Enqueue root and None node
    q.append(root)
 
    # Stores Nodes of
    # Current Level
    while q:
        n = len(q)
        flag0 = 0
        flag1 = 0
        flag2 = 0
 
        while (n):
 
            # Stores first node of
            # the current level
            curr = q[0]
            q.popleft()
 
            if (curr):
 
                # If left child exists
                if (curr.left):
 
                    # Push into the Queue
                    q.append(curr.left)
 
                # If right child exists
                if (curr.right):
 
                    # Push into the Queue
                    q.append(curr.right)
 
                if (curr.data == 1):
 
                    # If current node is the first
                    # node with value 1
                    if (not flag1):
                        flag1 = 1
 
                    # If current node has value 1
                    # after occurrence of nodes
                    # with value 0 following a
                    # sequence of nodes with value 1
                    if (flag1 and flag0):
                        flag2 = 1
 
                # If current node is the first node
                # with value 0 after a sequence
                # of nodes with value 1
                if (curr.data == 0 and flag1):
                    flag0 = 1
 
            n -= 1
 
        if (flag1 and not flag2):
            Count += 1
 
    return Count
 
# Function to create a Tree Node
def newNode(data):
 
    temp = node()
    temp.data = data
    temp.left = None
    temp.right = None
    return temp
 
# Driver Code
if __name__ == "__main__":
 
    root = newNode(0)
    root.left = newNode(0)
    root.right = newNode(1)
    root.left.left = newNode(0)
    root.left.right = newNode(1)
    root.right.left = newNode(1)
    root.right.right = newNode(0)
 
    print(countLevels(root))
 
# This code is contributed by sanjeev2552


C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A Binary Tree Node
class node
{
 
    // Left Child
    public node left;
    public int data;
 
    // Right Child
    public node right;
};
 
// Function to perform level order traversal
// count levels with all 1s grouped together
static int countLevels(node root)
{
    if (root == null)
        return 0;
    int Count = 0;
 
    // Create an empty queue for
    // level order traversal
    Queue q = new Queue();
 
    // Stores front element of the queue
    node curr;
 
    // Enqueue root and null node
    q.Enqueue(root);
 
    // Stores Nodes of
    // Current Level
    while (q.Count != 0)
    {
        int n = q.Count;
        int flag0 = 0, flag1 = 0, flag2 = 0;
        while (n-- >0)
        {
 
            // Stores first node of
            // the current level
            curr = q.Peek();
            q.Dequeue();
            if (curr != null)
            {
 
                // If left child exists
                if (curr.left != null)
 
                    // Push into the Queue
                    q.Enqueue(curr.left);
 
                // If right child exists
                if (curr.right != null)
 
                    // Push into the Queue
                    q.Enqueue(curr.right);
 
                if (curr.data == 1)
                {
 
                    // If current node is the first
                    // node with value 1
                    if (flag1 == 0)
                        flag1 = 1;
 
                    // If current node has value 1
                    // after occurrence of nodes
                    // with value 0 following a
                    // sequence of nodes with value 1
                    if (flag1 > 0 && flag0 > 0)
                        flag2 = 1;
                }
 
                // If current node is the first node
                // with value 0 after a sequence
                // of nodes with value 1
                if (curr.data == 0 && flag1 > 0)
                    flag0 = 1;
            }
        }
        if (flag1 > 0 && flag2 == 0)
            Count++;
    }
    return Count;
}
 
// Function to create a Tree Node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver Code
public static void Main(String[] args)
{
    node root = newNode(0);
    root.left = newNode(0);
    root.right = newNode(1);
    root.left.left = newNode(0);
    root.left.right = newNode(1);
    root.right.left = newNode(1);
    root.right.right = newNode(0);
    Console.Write(countLevels(root));
}
}
 
// This code is contributed by 29AjayKumar


输出:
2

时间复杂度: O(N)
辅助空间: O(N)