📜  计算二叉树中存在的平衡节点

📅  最后修改于: 2021-09-03 04:07:21             🧑  作者: Mango

给定一棵二叉树,任务是计算给定树中平衡节点的数量。

例子:

方法:这个想法是递归遍历给定二叉树的每个节点。对于每个节点,计算左右子树中节点的总和,并检查计算的总和是否相等。如果发现是真的,增加计数。最后,在完全遍历树后打印计数

请按照以下步骤解决问题:

  1. 初始化一个变量res来存储平衡节点的数量
  2. 递归计算每个节点的左右子树之和。
  3. 检查计算的总和是否相等。
  4. 如果发现为真,则当前节点是平衡的。因此,将res增加1
  5. 最后,在完全遍历树后打印res的值。

下面是上述方法的实现:

C++
9
                 /  \
                2   4 
               / \   \
             -1   3   0


Java
7
                 / \
                4  10
              /  \     
            3    3
          / \     \
        0    0    -3
                  /
                 3


Python3
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Structure of a
// Tree Node
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val)
    {
        data = val;
        left = right = NULL;
    }
};
 
// Function to get the sum of left
// subtree and right subtree
int Sum(Node* root, int& res)
{
    // Base case
    if (root == NULL) {
        return 0;
    }
 
    // Store the sum of
    // left subtree
    int leftSubSum
        = Sum(root->left, res);
 
    // Store the sum of
    // right subtree
    int rightSubSum
        = Sum(root->right, res);
 
    // Check if node is balanced or not
    if (root->left and root->right
        && leftSubSum == rightSubSum)
 
        // Increase count of
        // balanced nodes
        res += 1;
 
    // Return subtree sum
    return root->data + leftSubSum
           + rightSubSum;
}
 
// Driver Code
int main()
{
 
    /*
                   9
                 /  \
                2   4
               / \   \
             -1   3   0
    */
 
    // Insert nodes in tree
    Node* root = new Node(9);
    root->left = new Node(2);
    root->left->left = new Node(-1);
    root->left->right = new Node(3);
    root->right = new Node(4);
    root->right->right = new Node(0);
 
    // Store the count of balanced nodes
    int res = 0;
    Sum(root, res);
    cout << res;
}


C#
// Java program to implement
// the above approach
class GFG{
     
static int res = 0;
   
// Structure of a
// Tree Node
static class Node
{
  int data;
  Node left;
  Node right;
  Node(int val)
  {
    data = val;
    left = right = null;
  }
};
 
// Function to get the sum of left
// subtree and right subtree
static int Sum(Node root)
{
  // Base case
  if (root == null)
  {
    return 0;
  }
 
  // Store the sum of
  // left subtree
  int leftSubSum = Sum(root.left);
 
  // Store the sum of
  // right subtree
  int rightSubSum = Sum(root.right);
 
  // Check if node is balanced or not
  if (root.left != null && root.right != null &&
      leftSubSum == rightSubSum)
 
    // Increase count of
    // balanced nodes
    res += 1;
 
  // Return subtree sum
  return root.data + leftSubSum +
         rightSubSum;
}
 
// Driver Code
public static void main(String[] args)
{
  /*
                   9
                 /  \
                2   4
               / \   \
             -1   3   0
    */
 
  // Insert nodes in tree
  Node root = new Node(9);
  root.left = new Node(2);
  root.left.left = new Node(-1);
  root.left.right = new Node(3);
  root.right = new Node(4);
  root.right.right = new Node(0);
 
  // Store the count of balanced nodes
  res = 0;
  Sum(root);
  System.out.print(res);
}
}
 
// This code is contributed by 29AjayKumar


输出:
# Python3 program to implement
# the above approach
 
# Structure of a  Tree Node
class Node:
    def __init__(self, val):
         
        self.data = val
        self.left = None
        self.right = None
 
# Function to get the sum of left
# subtree and right subtree
def Sum(root):
 
    global res
 
    # Base case
    if (root == None):
        return 0
 
    # Store the sum of
    # left subtree
    leftSubSum = Sum(root.left)
 
    # Store the sum of
    # right subtree
    rightSubSum = Sum(root.right)
 
    # Check if node is balanced or not
    if (root.left and root.right and
       leftSubSum == rightSubSum):
 
        # Increase count of
        # balanced nodes
        res += 1
 
    # Return subtree sum
    return (root.data + leftSubSum +
                        rightSubSum)
 
# Driver Code
"""
                  9
                 / \
                2   4 
               / \   \
             -1   3   0
"""
# Insert nodes in tree
root = Node(9)
root.left = Node(2)
root.left.left = Node(-1)
root.left.right = Node(3)
root.right = Node(4)
root.right.right = Node(0)
 
# Store the count of balanced nodes
global res
res = 0
Sum(root)
print(res)
 
# This code is contributed by Shivam Singh

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live