给定一个由N 个节点组成的二叉树,任务是找到给定树中每个级别的所有叶节点之和与所有非叶节点之和的 Bitwise AND 之和。
例子:
Input: Below is the given tree:
5
/ \
3 9
/ \
6 4
\
7
Output: 5
Explanation:
For Level 1: leaf node sum = 0, non-leaf node sum = 5. So, 0&5 = 0.
For Level 2: leaf node sum = 9, non-leaf node sum = 3. So, 9&3 = 1.
For Level 3: leaf node sum = 4, non-leaf node sum = 6. So, 6&4 = 4.
For Level 4: leaf node sum = 7, non-leaf node sum = 0. So, 0&7 = 0.
Hence, the total sum is 0 + 1 + 4 + 0 = 5.
Input: Below is the given tree:
4
/ \
9 3
/ \
5 3
Output: 1
Explanation:
For Level 1: leaf node sum = 0, non-leaf node sum = 4. So, 0&4 = 0
For Level 2: leaf node sum = 9, non-leaf node sum = 3. So, 9&3 = 1
For Level 3: leaf node sum = 8, non-leaf node sum = 0. So, 8&0 = 0
Hence, the total sum is 0 + 1 + 0 = 1
方法:解决上述问题的思路是对树进行Level Order Traversal。在做遍历的时候,分别处理不同层次的节点,对于每一个被处理的层次,求每一层次的叶子节点和非叶子节点的总和。请按照以下步骤解决问题:
- 初始化一个队列Q并将根节点推送到它并将ans初始化为0以存储所需的答案。
- 执行以下步骤直到Q不为空:
- 初始化leafSum为0和nonLeafSum为0到分别存储在目前的水平叶节点和非叶节点的总和。
- 找出队列Q的当前大小并设为L 。
- 迭代范围[0, L]并执行以下操作:
- 从队列中弹出节点。
- 如果弹出的节点是叶节点,则将该值添加到LeafSum否则将其添加到nonLeafSum 。
- 如果存在,则将当前弹出节点的左右子节点推入队列。
- 对于当前级别,将LeafSum和nonLeafSum的按位与添加到变量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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live