📌  相关文章
📜  数据结构示例-查找一棵二叉树的所有节点的总和

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

Q.程序来查找二叉树的所有节点的总和

说明

在此程序中,我们需要计算二叉树中存在的节点总数。首先,我们将遍历左侧子树并计算左侧子树中存在的节点总数。同样,我们计算右子树中存在的节点总数,并通过添加根的数据来计算总数。

对于给定的树,二叉树的节点总数为1 + 2 + 5 + 8 + 6 + 9 = 31。

算法

  • 定义具有三个属性的Node类,即:左和右数据。在此,左代表节点的左子节点,右代表节点的右子节点。
  • 创建节点时,数据将传递到该节点的data属性,并且左右都将设置为null。
  • 定义另一个具有属性根的类。
    1. 表示树的根节点,并将其初始化为null。
  • computeSum()将计算二叉树中存在的节点总数:
    1. 它检查是否为null ,这表示树为空。
    2. 如果树不为空,请遍历左子树,计算节点的总和并将其存储在sumLeft中。
    3. 然后,遍历右子树,计算节点的总和并将其存储在sumRight中。
    4. 最后,计算总和=临时数据+ sumLeft + sumRight。

示例:

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 SumOfNodes:
    def __init__(self):
        #Represent the root of binary tree
        self.root = None;
    
    #calculateSum() will calculate the sum of all the nodes present in the binary tree
    def calculateSum(self, temp):
        sum = sumRight = sumLeft = 0;
        
        #Check whether tree is empty
        if(self.root == None):
            print("Tree is empty");
            return 0;
        else:
            #Calculate the sum of nodes present in left subtree
            if(temp.left != None):
                sumLeft = self.calculateSum(temp.left);
            
            #Calculate the sum of nodes present in right subtree
            if(temp.right != None):
                sumRight = self.calculateSum(temp.right);
            
            #Calculate the sum of all nodes by adding sumLeft, sumRight and root node's data
            sum = temp.data + sumLeft + sumRight; 
        return sum;
 
bt = SumOfNodes();
#Add nodes to the binary tree
bt.root = Node(5);
bt.root.left = Node(2);
bt.root.right = Node(9);
bt.root.left.left = Node(1);
bt.root.right.left = Node(8);
bt.root.right.right = Node(6);
 
#Display the sum of all the nodes in the given binary tree
print("Sum of all nodes of binary tree: " + str(bt.calculateSum(bt.root)));

输出:

Sum of all nodes of binary tree: 31

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;
}
 
//calculateSum() will calculate the sum of all the nodes present in the binary tree
int calculateSum(struct node *temp){
    int sum, sumLeft, sumRight;
    sum = sumRight = sumLeft = 0;
    
    //Check whether tree is empty
    if(root == NULL) {
        printf("Tree is empty\n");
        return 0;
    }
    else {
        //Calculate the sum of nodes present in left subtree
        if(temp->left != NULL)
            sumLeft = calculateSum(temp->left);
        
        //Calculate the sum of nodes present in right subtree
        if(temp->right != NULL)
              sumRight = calculateSum(temp->right);
        
        //Calculate the sum of all nodes by adding sumLeft, sumRight and root node's data
        sum = temp->data + sumLeft + sumRight; 
        return sum;
  }    
}
 
int main()
{
    //Add nodes to the binary tree
    root = createNode(5);
    root->left = createNode(2);
    root->right = createNode(9);
    root->left->left = createNode(1);
    root->right->left = createNode(8);
    root->right->right = createNode(6);
    
    //Display the sum of all the nodes in the given binary tree
    printf("Sum of all nodes of binary tree: %d", calculateSum(root));
    return 0;
}

输出:

Sum of all nodes of binary tree: 31

JAVA

public class SumOfNodes {
      
      //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 SumOfNodes(){
        root = null;
      }
      
      //calculateSum() will calculate the sum of all the nodes present in the binary tree
      public int calculateSum(Node temp){
        int sum, sumLeft, sumRight;
        sum = sumRight = sumLeft = 0;
        
        //Check whether tree is empty
        if(root == null) {
            System.out.println("Tree is empty");
            return 0;
        }
        else {
            //Calculate the sum of nodes present in left subtree
            if(temp.left != null)
                sumLeft = calculateSum(temp.left);
            
            //Calculate the sum of nodes present in right subtree
            if(temp.right != null)
                sumRight = calculateSum(temp.right);
            
            //Calculate the sum of all nodes by adding sumLeft, sumRight and root node's data
            sum = temp.data + sumLeft + sumRight; 
            return sum;
        }    
      }
      
      public static void main(String[] args) {
        
        SumOfNodes bt = new SumOfNodes();
        //Add nodes to the binary tree
        bt.root = new Node(5);
        bt.root.left = new Node(2);
        bt.root.right = new Node(9);
        bt.root.left.left = new Node(1);
        bt.root.right.left = new Node(8);
        bt.root.right.right = new Node(6);
        
        //Display the sum of all the nodes in the given binary tree
        System.out.println("Sum of all nodes of binary tree: " + bt.calculateSum(bt.root));
      }
    }

输出:

Sum of all nodes of binary tree: 31

C#

using System;
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 SumOfNodes{
            //Represent the root of binary tree
            public Node root;
 
            public static Boolean flag = false;
 
            public SumOfNodes(){
                root = null;
            }
        
        //calculateSum() will calculate the sum of all the nodes present in the binary tree
          public int calculateSum(Node temp){
            int sum, sumLeft, sumRight;
            sum = sumRight = sumLeft = 0;
            
            //Check whether tree is empty
            if(root == null) {
                Console.WriteLine("Tree is empty");
                return 0;
            }
            else {
                //Calculate the sum of nodes present in left subtree
                if(temp.left != null)
                    sumLeft = calculateSum(temp.left);
                
                //Calculate the sum of nodes present in right subtree
                if(temp.right != null)
                    sumRight = calculateSum(temp.right);
                
                //Calculate the sum of all nodes by adding sumLeft, sumRight and root node's data
                sum = (int)(object)temp.data + sumLeft + sumRight; 
                return sum;
            }    
          }
    }    
        public static void Main()
        {
            SumOfNodes bt = new SumOfNodes();
            //Add nodes to the binary tree
            bt.root = new Node(5);
            bt.root.left = new Node(2);
            bt.root.right = new Node(9);
            bt.root.left.left = new Node(1);
            bt.root.right.left = new Node(8);
            bt.root.right.right = new Node(6);
            
            //Display the sum of all the nodes in the given binary tree
            Console.WriteLine("Sum of all nodes of binary tree: " + bt.calculateSum(bt.root));            
        }    
    }
}

输出:

Sum of all nodes of binary tree: 31

PHP:




data = $data;
        $this->left = NULL;
        $this->right = NULL;
    }
}
class SumOfNodes{
    //Represent the root of binary tree
    public $root;
    function __construct(){
        $this->root = NULL;
    }
    
    //calculateSum() will calculate the sum of all the nodes present in the binary tree
    function calculateSum($temp){
        $sum = 0;
        $sumLeft = 0;
        $sumRight = 0;
      
        //Check whether tree is empty
        if($this->root == NULL) {
            print "Tree is empty 
"; return 0; } else { //Calculate the sum of nodes present in left subtree if($temp->left != NULL) $sumLeft = $this->calculateSum($temp->left); //Calculate the sum of nodes present in right subtree if($temp->right != NULL) $sumRight = $this->calculateSum($temp->right); //Calculate the sum of all nodes by adding sumLeft, sumRight and root node's data $sum = $temp->data + $sumLeft + $sumRight; return $sum; } } } $bt = new SumOfNodes(); //Add nodes to the binary tree $bt->root = new Node(5); $bt->root->left = new Node(2); $bt->root->right = new Node(9); $bt->root->left->left = new Node(1); $bt->root->right->left = new Node(8); $bt->root->right->right = new Node(6); //Display the sum of all the nodes in the given binary tree print "Sum of all nodes of binary tree: " . $bt->calculateSum($bt->root); ?>

输出:

Sum of all nodes of binary tree: 31