📌  相关文章
📜  数据结构示例-确定一棵二叉树的最大宽度

📅  最后修改于: 2020-10-15 06:26:28             🧑  作者: Mango

问:查找二叉树的最大宽度的程序

说明

在此程序中,我们需要找出二叉树的最大宽度。二叉树的宽度是任何级别中存在的节点数。因此,具有最大节点数的级别将是二叉树的最大宽度。要解决此问题,请逐级遍历树并计算每个级别中的节点。

在给定的二叉树中

级别1有一个节点,因此maxWidth =1。级别2有两个节点,因此maxWidth = 2为(2> 1)。级别3具有四个节点,因此maxWidth = 4为(4> 2)。级别4具有一个节点,因此maxWidth = 4为(1 <4)。

因此,上述二叉树的最大宽度为4,用白色椭圆表示。

算法

  • 定义具有三个属性的Node类,即: leftright数据。在此,左代表节点的左子节点,右代表节点的右子节点。
  • 创建节点时,数据将传递到该节点的data属性,并且left和right都将设置为null
  • 定义另一个具有属性根的类。
    1. 表示树的根节点,并将其初始化为null。
  • findMaximumWidth()将找出给定二叉树的最大宽度:
    1. 变量maxWidth将存储任何级别中存在的最大节点数。
    2. 该队列用于逐级遍历二叉树。
    3. 它检查是否为null ,这表示树为空。
    4. 如果不是,则将根节点添加到队列中。变量nodesInLevel跟踪每个级别中的节点数。
    5. 如果nodesInLevel> 0,请从队列的前面删除该节点,并将其左右子节点添加到队列中。对于第一次迭代,将删除节点1并将其子节点2和3添加到队列中。在第二次迭代中,将删除节点2,将其子级4和5添加到队列中,依此类推。
    6. MaxWidth将存储max(maxWidth,nodesInLevel)。因此,在任何给定的时间点,它将代表最大的节点数。
    7. 这将一直持续到遍历树的所有级别为止。

示例:

Python

#Represent a node of binary tree
class Node:
    def __init__(self,data):
        #Assign data to the new node, set left and right children to None
        self.data = data;
        self.left = None;
        self.right = None;
 
class BinaryTree:
    def __init__(self):
        #Represent the root of binary tree
        self.root = None;
    
    #findMaximumWidth() will find out the maximum width of the given binary tree
    def findMaximumWidth(self):
        maxWidth = 0;
        #Variable nodesInLevel keep tracks of number of nodes in each level
        nodesInLevel = 0;
        #queue will be used to keep track of nodes of tree level-wise
        queue = [];
        
        #Check if root is null, then width will be 0
        if(self.root == None):
            print("Tree is empty");
            return 0;
        else:
            #Add root node to queue as it represents the first level
            queue.append(self.root);
            
            while(len(queue) != 0):
                
                #Variable nodesInLevel will hold the size of queue i.e. number of elements in queue
                nodesInLevel = len(queue);
                #maxWidth will hold maximum width. 
                #If nodesInLevel is greater than maxWidth then, maxWidth will hold the value of nodesInLevel
                maxWidth = max(maxWidth, nodesInLevel);
                
                #If variable nodesInLevel contains more than one node 
                #then, for each node, we'll add left and right child of the node to the queue
                while(nodesInLevel > 0):
                    current = queue.pop(0);
                    if(current.left != None):
                        queue.append(current.left);
                    if(current.right != None):
                        queue.append(current.right);
                    nodesInLevel = nodesInLevel - 1;
        return maxWidth;
 
bt = BinaryTree();
#Add nodes to the binary tree
bt.root = Node(1);
bt.root.left = Node(2);
bt.root.right = Node(3);
bt.root.left.left = Node(4);
bt.root.left.right = Node(5);
bt.root.right.left = Node(6);
bt.root.right.right = Node(7);
bt.root.left.left.left = Node(8);
 
#Display the maximum width of given tree
print("Maximum width of the binary tree: " + str(bt.findMaximumWidth()));

输出:

Maximum width of the binary tree: 4

C

#include 
#include 
 
//Represent a node of binary tree
struct node{
    int data;
    struct node *left;
    struct node *right;
};
 
//Represent the root of binary tree
struct node *root = NULL;
 
//createNode() will create a new node
struct node* createNode(int data){
    //Create a new node
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    //Assign data to newNode, set left and right children to NULL
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    
    return newNode;
}
 
//queue will be used to keep track of nodes of tree level-wise
struct node* queue[100];
int rear = 0,front = -1, size = 0;
 
//Adds new node to the queue
void enqueue(struct node* temp)
{
    queue[rear++]=temp;
    size++;
}
//Deletes a node from the queue
struct node* dequeue()
{
    size--;
    return queue[++front];
}
 
//findMaximumWidth() will find out the maximum width of the given binary tree
int findMaximumWidth() {
    int maxWidth = 0;
    
    //Variable nodesInLevel keep tracks of number of nodes in each level
    int nodesInLevel = 0;
    
    //Check if root is null, then width will be 0
    if(root == NULL) {
        printf("Tree is empty\n");
        return 0;
    }
    else {
        //Add root node to queue as it represents the first level
        enqueue(root);
        
        while(size != 0) {
            //Variable nodesInLevel will hold the size of queue i.e. number of elements in queue
            nodesInLevel = size;
            
            //maxWidth will hold maximum width. 
            //If nodesInLevel is greater than maxWidth then, maxWidth will hold the value of nodesInLevel
            maxWidth = (maxWidth < nodesInLevel) ? nodesInLevel : maxWidth;
 
            //If variable nodesInLevel contains more than one node 
            //then, for each node, we'll add left and right child of the node to the queue
            while(nodesInLevel > 0) {
                    
                struct node *current = dequeue();
                if(current->left != NULL){
                    enqueue(current->left);    
                }
                
                if(current->right != NULL) {
                    enqueue(current->right);    
                }
                nodesInLevel--;
            }
        }
    return maxWidth;
    }
}
 
int main()
{
    //Add nodes to the binary tree
    root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->left = createNode(6);
    root->right->right = createNode(7);
    root->left->left->left = createNode(8);
    
    //Display the maximum width of the given tree
    printf("Maximum width of the binary tree: %d", findMaximumWidth());
    return 0;
}

输出:

Maximum width of the binary tree: 4

JAVA

import java.util.LinkedList;
import java.util.Queue;
 
public class BinaryTree {
    
      //Represent the node of binary tree
      public static class Node{
        int data;
        Node left;
        Node right;
        
        public Node(int data){
          //Assign data to the new node, set left and right children to null
          this.data = data;
          this.left = null;
          this.right = null;
        }
      }
      
      //Represent the root of binary tree
      public Node root;
      
      public BinaryTree(){
        root = null;
      }
      
      //findMaximumWidth() will find out the maximum width of the given binary tree
      public int findMaximumWidth() {
          int maxWidth = 0;
          
          //Variable nodesInLevel keep tracks of number of nodes in each level
          int nodesInLevel = 0;
          //queue will be used to keep track of nodes of tree level-wise
          Queue queue = new LinkedList();
          
          //Check if root is null, then width will be 0
          if(root == null) {
              System.out.println("Tree is empty");
              return 0;
          }
          else {
              //Add root node to queue as it represents the first level
              queue.add(root);
              
              while(queue.size() != 0) {
                  
                  //Variable nodesInLevel will hold the size of queue i.e. number of elements in queue
                  nodesInLevel = queue.size();
                  //maxWidth will hold maximum width. 
                  //If nodesInLevel is greater than maxWidth then, maxWidth will hold the value of nodesInLevel
                  maxWidth = Math.max(maxWidth, nodesInLevel);
                  
                  //If variable nodesInLevel contains more than one node 
                  //then, for each node, we'll add left and right child of the node to the queue
                  while(nodesInLevel > 0) {
                     Node current = queue.remove();
                     if(current.left != null) 
                         queue.add(current.left);
                     if(current.right != null) 
                         queue.add(current.right);
                     nodesInLevel--;
                  }
              }
          }
          return maxWidth;
      }
      
      public static void main(String[] args) {
          
          BinaryTree bt = new BinaryTree();
          //Add nodes to the binary tree
          bt.root = new Node(1);
          bt.root.left = new Node(2);
          bt.root.right = new Node(3);
          bt.root.left.left = new Node(4);
          bt.root.left.right = new Node(5);
          bt.root.right.left = new Node(6);
          bt.root.right.right = new Node(7);
          bt.root.left.left.left = new Node(8);
          
          //Display the maximum width of given tree
          System.out.println("Maximum width of the binary tree: " + bt.findMaximumWidth());
      }
}

输出:

Maximum width of the binary tree: 4

C#

using System;
using System.Collections.Generic;
namespace Tree 
{                     
    public class Program
    {
        //Represent a node of binary tree
        public class Node{
            public T data;
            public Node left;
            public Node right;
            
            public Node(T data) {
                //Assign data to the new node, set left and right children to null
                this.data = data;
                this.left = null;
                this.right = null;
            }
        }
        
        public class BinaryTree where T : IComparable{
            //Represent the root of binary tree
            public Node root;
 
            public static Boolean flag = false;
 
            public BinaryTree(){
                root = null;
            }
        
        //findMaximumWidth() will find out the maximum width of the given binary tree
          public int findMaximumWidth() {
            int maxWidth = 0;
            
            //Variable nodesInLevel keep tracks of number of nodes in each level
            int nodesInLevel = 0;
            //queue will be used to keep track of nodes of tree level-wise
            Queue> queue = new Queue>();
            
            //Check if root is null, then width will be 0
            if(root == null) {
              Console.WriteLine("Tree is empty");
              return 0;
            }
            else {
              //Add root node to queue as it represents the first level
              queue.Enqueue(root);
              
              while(queue.Count != 0) {
                  
                  //Variable nodesInLevel will hold the size of queue i.e. number of elements in queue
                  nodesInLevel = queue.Count;
                  //maxWidth will hold maximum width. 
                  //If nodesInLevel is greater than maxWidth then, maxWidth will hold the value of nodesInLevel
                  maxWidth = (maxWidth < nodesInLevel) ? nodesInLevel : maxWidth;
                  
                  //If variable nodesInLevel contains more than one node 
                  //then, for each node, we'll add left and right child of the node to the queue
                  while(nodesInLevel > 0) {
                     Node current = queue.Dequeue();
                     if(current.left != null) 
                         queue.Enqueue(current.left);
                     if(current.right != null) 
                         queue.Enqueue(current.right);
                     nodesInLevel = nodesInLevel - 1;
                  }
              }
            }
            return maxWidth;
      }
        }
        
        public static void Main()
        {
            BinaryTree bt = new BinaryTree();
            //Add nodes to the binary tree
              bt.root = new Node(1);
              bt.root.left = new Node(2);
              bt.root.right = new Node(3);
              bt.root.left.left = new Node(4);
              bt.root.left.right = new Node(5);
              bt.root.right.left = new Node(6);
              bt.root.right.right = new Node(7);
              bt.root.left.left.left = new Node(8);
          
              //Display the maximum width of given tree
              Console.WriteLine("Maximum width of the binary tree: " + bt.findMaximumWidth());                
        }    
    }
}

输出:

Maximum width of the binary tree: 4

PHP:




data = $data;
        $this->left = NULL;
        $this->right = NULL;
    }
}
class BinaryTree{
    //Represent the root of binary tree
    public $root;
    function __construct(){
        $this->root = NULL;
    }
    
    //findMaximumWidth() will find out the maximum width of the given binary tree
    function findMaximumWidth() {
      $maxWidth = 0;
      
      //Variable $nodesInLevel keep tracks of number of nodes in each level
      $nodesInLevel = 0;
      //$queue will be used to keep track of nodes of tree level-wise
      $queue = array();
      
      //Check if root is null, then width will be 0
      if($this->root == null) {
          print "Tree is empty 
"; return 0; } else { //Add root node to $queue as it represents the first level array_push($queue,$this->root); while(sizeof($queue) != 0) { //Variable $nodesInLevel will hold the size of queue i.e. number of elements in queue $nodesInLevel = sizeof($queue); //$maxWidth will hold maximum width. //If $nodesInLevel is greater than $maxWidth then, $maxWidth will hold the value of $nodesInLevel $maxWidth = max($maxWidth, $nodesInLevel); //If variable $nodesInLevel contains more than one node //then, for each node, we'll add left and right child of the node to the $queue while($nodesInLevel > 0) { $current = array_shift($queue); if($current->left != NULL) array_push($queue, $current->left); if($current->right != NULL) array_push($queue,$current->right); $nodesInLevel--; } } } return $maxWidth; } } $bt = new BinaryTree(); //Add nodes to the binary tree $bt->root = new Node(1); $bt->root->left = new Node(2); $bt->root->right = new Node(3); $bt->root->left->left = new Node(4); $bt->root->left->right = new Node(5); $bt->root->right->left = new Node(6); $bt->root->right->right = new Node(7); $bt->root->left->left->left = new Node(8); //Display the maximum width of given tree print "Maximum width of the binary tree: " . $bt->findMaximumWidth(); ?>

输出:

Maximum width of the binary tree: 4