📌  相关文章
📜  二叉树每个级别的所有叶子节点和非叶子节点的总和的按位与之和

📅  最后修改于: 2021-04-17 16:48:53             🧑  作者: Mango

给定一个由N个节点组成的二叉树,任务是查找给定树中每个级别的所有叶子节点的总和与所有非叶子节点的总和的按位与之和。

例子:

方法:解决上述问题的想法是执行树的“级别顺序遍历”。遍历时,分别处理不同级别的节点,并针对每个要处理的级别,找到每个级别的叶子节点和非叶子节点的总和。请按照以下步骤解决问题:

  • 初始化队列Q并将根节点推送到该队列,然后将ans初始化为0以存储所需的答案。
  • 执行以下步骤,直到Q不为空:
    • 初始化leafSum0nonLeafSum0到分别存储在目前的水平叶节点和非叶节点的总和。
    • 找到队列Q的当前大小,并将其设为L。
    • 遍历范围[0,L]并执行以下操作:
      • 从队列中弹出节点。
      • 如果弹出节点是叶节点,则将值添加到leafSum,否则将其添加到nonLeafSum
      • 将当前弹出节点的左右子节点(如果存在)推入队列。
    • 对于当前级别,将leafSumnonLeafSum按位与运算符添加到变量ans中
  • 完成上述步骤后,输出ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for given approach
#include
using namespace std;
 
// Structure of a Binary tree node
struct TreeNode
{
  int val;
  TreeNode *left,*right;
   
  // Helper function to allocate
  // a new node with the given data
  // and left and right pointers as None
    TreeNode(int x = 0)
    {
        val = x;
        left = NULL;
        right = NULL;
   }
};
 
// Function to calculate the sum of
// bitwise AND of the sum of all leaf
// nodes and non-leaf nodes for each level
int findSum(TreeNode *root){
 
    // Initialize a queue and
    // append root to it
    queue que;
 
    que.push(root);
     
  // Store the required answer
    int ans = 0;
    while (que.size())
    {
 
        // Stores the sum of leaf nodes
        // at the current level
        int leaf = 0;
 
        // Stores the sum of non-leaf
        // nodes at the current level
        int nonleaf = 0;
 
        // Get the size of the queue
        int length = que.size();
 
        // Iterate for all the nodes
        // in the queue currently
        while (length)
        {
 
            // Dequeue a node from queue
            auto temp = que.front();
            que.pop();
 
            // Check if the node is a
            // leaf node
            if (!temp->left && !temp->right)
               
                // If true, update the
                // leaf node sum
                leaf += temp->val;
           
            // Otherwise, update the
            // non-leaf node sum
            else
                nonleaf += temp->val;
 
            // Enqueue left and right
            // children of removed node
            if (temp->left)
                que.push(temp->left);
            if (temp->right)
                que.push(temp->right);
 
            length -= 1;
        }
 
        // Update the answer
        ans += leaf & nonleaf;
      }
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
   
  // Given Tree
  TreeNode *root = new TreeNode(5);
  root->left = new TreeNode(3);
  root->right = new TreeNode(9);
  root->left->left = new TreeNode(6);
  root->left->right = new TreeNode(4);
  root->left->left->right = new TreeNode(7);
   
  // Function Call
  cout<


Java
// Java program for given approach
import java.util.*;
class GFG
{
 
// Structure of a Binary tree node
static class TreeNode
{
  int val;
  TreeNode left,right;
   
  // Helper function to allocate
  // a new node with the given data
  // and left and right pointers as None
    TreeNode(int x)
    {
        val = x;
        left = null;
        right = null;
   }
};
 
// Function to calculate the sum of
// bitwise AND of the sum of all leaf
// nodes and non-leaf nodes for each level
static int findSum(TreeNode root)
{
 
    // Initialize a queue and
    // append root to it
    Queue que = new LinkedList<>();
 
    que.add(root);
     
  // Store the required answer
    int ans = 0;
    while (que.size() > 0)
    {
 
        // Stores the sum of leaf nodes
        // at the current level
        int leaf = 0;
 
        // Stores the sum of non-leaf
        // nodes at the current level
        int nonleaf = 0;
 
        // Get the size of the queue
        int length = que.size();
 
        // Iterate for all the nodes
        // in the queue currently
        while (length>0)
        {
 
            // Dequeue a node from queue
            TreeNode temp = que.peek();
            que.remove();
 
            // Check if the node is a
            // leaf node
            if (temp.left == null && temp.right == null)
               
                // If true, update the
                // leaf node sum
                leaf += temp.val;
           
            // Otherwise, update the
            // non-leaf node sum
            else
                nonleaf += temp.val;
 
            // Enqueue left and right
            // children of removed node
            if (temp.left != null)
                que.add(temp.left);
            if (temp.right != null)
                que.add(temp.right);
 
            length -= 1;
        }
 
        // Update the answer
        ans += leaf & nonleaf;
      }
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
   
  // Given Tree
  TreeNode root = new TreeNode(5);
  root.left = new TreeNode(3);
  root.right = new TreeNode(9);
  root.left.left = new TreeNode(6);
  root.left.right = new TreeNode(4);
  root.left.left.right = new TreeNode(7);
   
  // Function Call
  System.out.print(findSum(root));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python program for the above approach
 
# Structure of a Binary tree node
class TreeNode:
 
    # Helper function to allocate
    # a new node with the given data
    # and left and right pointers as None
    def __init__(self, val = 0, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to calculate the sum of
# bitwise AND of the sum of all leaf
# nodes and non-leaf nodes for each level
def findSum(root):
 
    # Initialize a queue and
    # append root to it
    que = [root]
 
    # Store the required answer
    ans = 0
 
    while (len(que)):
 
        # Stores the sum of leaf nodes
        # at the current level
        leaf = 0
 
        # Stores the sum of non-leaf
        # nodes at the current level
        nonleaf = 0
 
        # Get the size of the queue
        length = len(que)
 
        # Iterate for all the nodes
        # in the queue currently
        while length:
 
            # Dequeue a node from queue
            temp = que.pop(0)
 
            # Check if the node is a
            # leaf node
            if not temp.left and not temp.right:
 
                # If true, update the
                # leaf node sum
                leaf += temp.val
 
            # Otherwise, update the
            # non-leaf node sum
            else:
                nonleaf += temp.val
 
            # Enqueue left and right
            # children of removed node
            if temp.left:
                que.append(temp.left)
            if temp.right:
                que.append(temp.right)
 
            length -= 1
 
        # Update the answer
        ans += leaf & nonleaf
 
    # Return the answer
    return ans
 
 
# Driver Code
 
# Given Tree
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(9)
root.left.left = TreeNode(6)
root.left.right = TreeNode(4)
root.left.left.right = TreeNode(7)
 
# Function Call
print(findSum(root))


C#
// C# program for given approach
 
using System;
using System.Collections.Generic;
 
// Structure of a Binary tree node
class GFG{
 
class TreeNode
{
  public int val;
  public TreeNode left,right;
};
   
  // Helper function to allocate
  // a new node with the given data
  // and left and right pointers as None
  static TreeNode newNode(int x)
    {
        TreeNode temp = new TreeNode();
        temp.val = x;
        temp.left = null;
        temp.right = null;
        return temp;
   }
 
// Function to calculate the sum of
// bitwise AND of the sum of all leaf
// nodes and non-leaf nodes for each level
static int findSum(TreeNode root){
 
    // Initialize a queue and
    // append root to it
    Queue que =new Queue();
 
    que.Enqueue(root);
     
  // Store the required answer
    int ans = 0;
    while (que.Count>0)
    {
 
        // Stores the sum of leaf nodes
        // at the current level
        int leaf = 0;
 
        // Stores the sum of non-leaf
        // nodes at the current level
        int nonleaf = 0;
 
        // Get the size of the queue
        int length = que.Count;
 
        // Iterate for all the nodes
        // in the queue currently
        while (length>0)
        {
 
            // Dequeue a node from queue
            TreeNode temp = que.Peek();
            que.Dequeue();
 
            // Check if the node is a
            // leaf node
            if (temp.left == null && temp.right==null)
               
                // If true, update the
                // leaf node sum
                leaf += temp.val;
           
            // Otherwise, update the
            // non-leaf node sum
            else
                nonleaf += temp.val;
 
            // Enqueue left and right
            // children of removed node
            if (temp.left!=null)
                que.Enqueue(temp.left);
            if (temp.right != null)
                que.Enqueue(temp.right);
 
            length -= 1;
        }
 
        // Update the answer
        ans += (leaf & nonleaf);
      }
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void Main()
{
   
  // Given Tree
  TreeNode root = newNode(5);
  root.left = newNode(3);
  root.right = newNode(9);
  root.left.left = newNode(6);
  root.left.right = newNode(4);
  root.left.left.right = newNode(7);
   
  // Function Call
  Console.WriteLine(findSum(root));
}
}
 
// This code is contributed by bgangwar59.


输出:
5

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