给定二叉树,任务是在给定的二叉树中找到所有特殊平衡节点的总和。
A specially balanced node in a Binary Tree contains the sum of nodes of one subtree(either left or right) as even and the sum of the other subtree as odd.
The nodes having only one child or no child can never be a balanced node.
例子:
Input: Below is the given Tree:
Output: 33
Explanation:
The specially balanced nodes are 11 and 22.
For Node 11:
The sum of left subtree is (23 + 13 + 9) = 45 which is Odd.
The sum of right subtree is (44 + 22 + 7 + 6 + 15) = 94 which is Even.
For Node 22:
The sum of left subtree is 6 which is Even.
The sum of right subtree is 15 which is Odd.
Therefore, the sum of specially balanced nodes is 11 + 22 = 33.
Input: Below is the given Tree:
Output: 16
Explanation:
The specially balanced nodes are 4 and 12.
For Node 4:
The sum of left subtree is 2 which is Even.
The sum of right subtree is 3 which is Odd.
For Node 12:
The sum of left subtree is 17 which is Odd.
The sum of right subtree is (16 + 4 + 9 + 2 + 3) = 34 which is Even.
Therefore, the sum of specially balanced nodes is 4 + 12 = 16.
方法:想法是使用递归在给定的Tree上执行DFS遍历,并根据给定的条件更新最终的总和。请按照以下步骤操作:
- 将totalSum初始化为0 ,以存储所有特殊平衡的节点之和。
- 在给定的树上执行DFS遍历,并检查以下内容:
- 如果该节点是叶节点,则返回该节点的值。
- 现在,如果当前节点不是叶节点,则对左和右子树进行递归遍历。
- 每次递归调用结束时,返回带有当前根值的左右子树的总和值。
- 检查返回的和是否满足特殊平衡节点的属性。如果发现为真,则将当前节点值添加到totalSum中。
- 完成上述步骤后,打印totalSum的值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Structure of Binary Tree
struct Node {
int data;
Node *left, *right;
};
// Function to create a new node
Node* newnode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
// Return the created node
return temp;
}
// Function to insert a node in the tree
Node* insert(string s, int i, int N,
Node* root, Node* temp)
{
if (i == N)
return temp;
// Left insertion
if (s[i] == 'L')
root->left = insert(s, i + 1, N,
root->left,
temp);
// Right insertion
else
root->right = insert(s, i + 1, N,
root->right,
temp);
// Return the root node
return root;
}
// Function to find sum of specially
// balanced nodes in the Tree
int SBTUtil(Node* root, int& sum)
{
// Base Case
if (root == NULL)
return 0;
if (root->left == NULL
&& root->right == NULL)
return root->data;
// Find the left subtree sum
int left = SBTUtil(root->left, sum);
// Find the right subtree sum
int right = SBTUtil(root->right, sum);
// Condition of specially
// balanced node
if (root->left && root->right) {
// Condition of specially
// balanced node
if ((left % 2 == 0
&& right % 2 != 0)
|| (left % 2 != 0
&& right % 2 == 0)) {
sum += root->data;
}
}
// Return the sum
return left + right + root->data;
}
// Function to build the binary tree
Node* build_tree(int R, int N,
string str[],
int values[])
{
// Form root node of the tree
Node* root = newnode(R);
int i;
// Insert nodes into tree
for (i = 0; i < N - 1; i++) {
string s = str[i];
int x = values[i];
// Create a new Node
Node* temp = newnode(x);
// Insert the node
root = insert(s, 0, s.size(),
root, temp);
}
// Return the root of the Tree
return root;
}
// Function to find the sum of specially
// balanced nodes
void speciallyBalancedNodes(
int R, int N, string str[], int values[])
{
// Build Tree
Node* root = build_tree(R, N,
str, values);
// Stores the sum of specially
// balanced node
int sum = 0;
// Function Call
SBTUtil(root, sum);
// Print required sum
cout << sum << " ";
}
// Driver Code
int main()
{
// Given nodes
int N = 7;
// Given root
int R = 12;
// Given path info of nodes
// from root
string str[N - 1]
= { "L", "R", "RL",
"RR", "RLL", "RLR" };
// Given node values
int values[N - 1] = { 17, 16, 4,
9, 2, 3 };
// Function Call
speciallyBalancedNodes(R, N, str,
values);
return 0;
}
Java
// Java program for
// the above approach
import java.util.*;
class GFG{
static int sum;
//Structure of Binary Tree
static class Node
{
int data;
Node left, right;
};
//Function to create a new node
static Node newnode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = null;
temp.right = null;
// Return the created node
return temp;
}
//Function to insert a node in the tree
static Node insert(String s, int i, int N,
Node root, Node temp)
{
if (i == N)
return temp;
// Left insertion
if (s.charAt(i) == 'L')
root.left = insert(s, i + 1, N,
root.left, temp);
// Right insertion
else
root.right = insert(s, i + 1, N,
root.right, temp);
// Return the root node
return root;
}
//Function to find sum of specially
//balanced nodes in the Tree
static int SBTUtil(Node root)
{
// Base Case
if (root == null)
return 0;
if (root.left == null &&
root.right == null)
return root.data;
// Find the left subtree sum
int left = SBTUtil(root.left);
// Find the right subtree sum
int right = SBTUtil(root.right);
// Condition of specially
// balanced node
if (root.left != null &&
root.right != null)
{
// Condition of specially
// balanced node
if ((left % 2 == 0 && right % 2 != 0) ||
(left % 2 != 0 && right % 2 == 0))
{
sum += root.data;
}
}
// Return the sum
return left + right + root.data;
}
//Function to build the binary tree
static Node build_tree(int R, int N,
String str[],
int values[])
{
// Form root node of the tree
Node root = newnode(R);
int i;
// Insert nodes into tree
for (i = 0; i < N - 1; i++)
{
String s = str[i];
int x = values[i];
// Create a new Node
Node temp = newnode(x);
// Insert the node
root = insert(s, 0, s.length(),
root, temp);
}
// Return the root of the Tree
return root;
}
// Function to find the
// sum of specially
// balanced nodes
static void speciallyBalancedNodes(int R, int N,
String str[],
int values[])
{
// Build Tree
Node root = build_tree(R, N, str,
values);
// Stores the sum of specially
// balanced node
sum = 0;
// Function Call
SBTUtil(root);
// Print required sum
System.out.print(sum + " ");
}
//Driver Code
public static void main(String[] args)
{
// Given nodes
int N = 7;
// Given root
int R = 12;
// Given path info of nodes
// from root
String str[] = {"L", "R", "RL",
"RR", "RLL", "RLR"};
// Given node values
int values[] = {17, 16, 4,
9, 2, 3};
// Function Call
speciallyBalancedNodes(R, N, str,
values);
}
}
//This code is contributed by 29AjayKumar
Python3
# Python3 program for the above approach
# Structure of Binary Tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to create a new node
def newnode(data):
temp = Node(data)
# Return the created node
return temp
# Function to insert a node in the tree
def insert(s, i, N, root, temp):
if (i == N):
return temp
# Left insertion
if (s[i] == 'L'):
root.left = insert(s, i + 1, N,
root.left, temp)
# Right insertion
else:
root.right = insert(s, i + 1, N,
root.right, temp)
# Return the root node
return root
# Function to find sum of specially
# balanced nodes in the Tree
def SBTUtil(root, sum):
# Base Case
if (root == None):
return [0, sum]
if (root.left == None and
root.right == None):
return [root.data, sum]
# Find the left subtree sum
left, sum = SBTUtil(root.left, sum)
# Find the right subtree sum
right, sum = SBTUtil(root.right, sum)
# Condition of specially
# balanced node
if (root.left and root.right):
# Condition of specially
# balanced node
if ((left % 2 == 0 and
right % 2 != 0) or
(left % 2 != 0 and
right % 2 == 0)):
sum += root.data
# Return the sum
return [left + right + root.data, sum]
# Function to build the binary tree
def build_tree(R, N, str, values):
# Form root node of the tree
root = newnode(R)
# Insert nodes into tree
for i in range(0, N - 1):
s = str[i]
x = values[i]
# Create a new Node
temp = newnode(x)
# Insert the node
root = insert(s, 0, len(s),
root, temp)
# Return the root of the Tree
return root
# Function to find the sum of specially
# balanced nodes
def speciallyBalancedNodes(R, N, str, values):
# Build Tree
root = build_tree(R, N, str, values)
# Stores the sum of specially
# balanced node
sum = 0
# Function Call
tmp, sum = SBTUtil(root, sum)
# Print required sum
print(sum, end = ' ')
# Driver code
if __name__ == "__main__":
# Given nodes
N = 7
# Given root
R = 12
# Given path info of nodes
# from root
str = [ "L", "R", "RL",
"RR", "RLL", "RLR" ]
# Given node values
values = [ 17, 16, 4, 9, 2, 3 ]
# Function Call
speciallyBalancedNodes(R, N, str,
values)
# This code is contributed by rutvik_56
C#
//C# program for
// the above approach
using System;
class GFG{
static int sum;
//Structure of Binary Tree
class Node
{
public int data;
public Node left, right;
};
//Function to create a new node
static Node newnode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = null;
temp.right = null;
// Return the created node
return temp;
}
//Function to insert a node in the tree
static Node insert(String s, int i, int N,
Node root, Node temp)
{
if (i == N)
return temp;
// Left insertion
if (s[i] == 'L')
root.left = insert(s, i + 1, N,
root.left, temp);
// Right insertion
else
root.right = insert(s, i + 1, N,
root.right, temp);
// Return the root node
return root;
}
//Function to find sum of specially
//balanced nodes in the Tree
static int SBTUtil(Node root)
{
// Base Case
if (root == null)
return 0;
if (root.left == null &&
root.right == null)
return root.data;
// Find the left subtree sum
int left = SBTUtil(root.left);
// Find the right subtree sum
int right = SBTUtil(root.right);
// Condition of specially
// balanced node
if (root.left != null &&
root.right != null)
{
// Condition of specially
// balanced node
if ((left % 2 == 0 && right % 2 != 0) ||
(left % 2 != 0 && right % 2 == 0))
{
sum += root.data;
}
}
// Return the sum
return left + right + root.data;
}
//Function to build the binary tree
static Node build_tree(int R, int N,
String []str,
int []values)
{
// Form root node of the tree
Node root = newnode(R);
int i;
// Insert nodes into tree
for (i = 0; i < N - 1; i++)
{
String s = str[i];
int x = values[i];
// Create a new Node
Node temp = newnode(x);
// Insert the node
root = insert(s, 0, s.Length,
root, temp);
}
// Return the root of the Tree
return root;
}
// Function to find the
// sum of specially
// balanced nodes
static void speciallyBalancedNodes(int R, int N,
String []str,
int []values)
{
// Build Tree
Node root = build_tree(R, N, str,
values);
// Stores the sum of specially
// balanced node
sum = 0;
// Function Call
SBTUtil(root);
// Print required sum
Console.Write(sum + " ");
}
//Driver Code
public static void Main(String[] args)
{
// Given nodes
int N = 7;
// Given root
int R = 12;
// Given path info of nodes
// from root
String []str = {"L", "R", "RL",
"RR", "RLL", "RLR"};
// Given node values
int []values = {17, 16, 4,
9, 2, 3};
// Function Call
speciallyBalancedNodes(R, N, str,
values);
}
}
// This code is contributed by 29AjayKumar
16
时间复杂度: O(N)
辅助空间: O(N)