将给定 N 叉树中的每个节点替换为其所有子树的总和
给定一个N叉树。任务是将每个节点的值替换为其所有子树和节点本身的总和。
例子
Input: 1
/ | \
2 3 4
/ \ \
5 6 7
Output: Initial Pre-order Traversal: 1 2 5 6 7 3 4
Final Pre-order Traversal: 28 20 5 6 7 3 4
Explanation: Value of each node is replaced by the sum of all its subtrees and the node itself.
Input: 1
/ | \
4 2 3
/ \ \
7 6 5
Output: Initial Pre-order Traversal: 1 4 7 6 3 5
Final Pre-order Traversal: 23 13 7 6 28 5
方法:这个问题可以通过递归来解决。请按照以下步骤解决给定的问题。
- 解决此问题的最简单方法是使用递归。
- 从当前节点等于 NULL时的基本条件开始,然后返回 0 ,因为这意味着它是叶节点。
- 否则,通过使用循环遍历并添加其中所有子节点的总和,对其所有子节点进行递归调用。
- 最后返回当前节点的数据。
- 这样,所有节点的值将被所有子树和自身的总和替换。
下面是上述方法的实现。
C++
// C++ implementation of the approach
#include
using namespace std;
// Class for the node of the tree
struct Node {
int data;
// List of children
struct Node** children;
int length;
Node()
{
length = 0;
data = 0;
}
Node(int n, int data_)
{
children = new Node*();
length = n;
data = data_;
}
};
// Function to replace node with
// sum of its left subtree, right
// subtree and its sum
int sumReplacementNary(Node* node)
{
if (node == NULL)
return 0;
// Total children count
int total = node->length;
// Taking sum of all the nodes
for (int i = 0; i < total; i++)
node->data += sumReplacementNary(node->children[i]);
return node->data;
}
void preorderTraversal(Node* node)
{
if (node == NULL)
return;
// Total children count
int total = node->length;
// Print the current node's data
cout << node->data << " ";
// All the children except the last
for (int i = 0; i < total - 1; i++)
preorderTraversal(node->children[i]);
// Last child
preorderTraversal(node->children[total - 1]);
}
// Driver code
int main()
{
/* Create the following tree
1
/ | \
2 3 4
/ \ \
5 6 7
*/
int N = 3;
Node* root = new Node(N, 1);
root->children[0] = new Node(N, 2);
root->children[1] = new Node(N, 3);
root->children[2] = new Node(N, 4);
root->children[0]->children[0] = new Node(N, 5);
root->children[0]->children[1] = new Node(N, 6);
root->children[0]->children[2] = new Node(N, 7);
cout << "Initial Pre-order Traversal: ";
preorderTraversal(root);
cout << endl;
cout << "Final Pre-order Traversal: ";
sumReplacementNary(root);
preorderTraversal(root);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG{
// Class for the node of the tree
static class Node {
int data;
// List of children
Node []children;
int length;
Node()
{
length = 0;
data = 0;
}
Node(int n, int data_)
{
children = new Node[n];
length = n;
data = data_;
}
};
// Function to replace node with
// sum of its left subtree, right
// subtree and its sum
static int sumReplacementNary(Node node)
{
if (node == null)
return 0;
// Total children count
int total = node.length;
// Taking sum of all the nodes
for (int i = 0; i < total; i++)
node.data += sumReplacementNary(node.children[i]);
return node.data;
}
static void preorderTraversal(Node node)
{
if (node == null)
return;
// Total children count
int total = node.length;
// Print the current node's data
System.out.print(node.data+ " ");
// All the children except the last
for (int i = 0; i < total - 1; i++)
preorderTraversal(node.children[i]);
// Last child
preorderTraversal(node.children[total - 1]);
}
// Driver code
public static void main(String[] args)
{
/* Create the following tree
1
/ | \
2 3 4
/ \ \
5 6 7
*/
int N = 3;
Node root = new Node(N, 1);
root.children[0] = new Node(N, 2);
root.children[1] = new Node(N, 3);
root.children[2] = new Node(N, 4);
root.children[0].children[0] = new Node(N, 5);
root.children[0].children[1] = new Node(N, 6);
root.children[0].children[2] = new Node(N, 7);
System.out.print("Initial Pre-order Traversal: ");
preorderTraversal(root);
System.out.println();
System.out.print("Final Pre-order Traversal: ");
sumReplacementNary(root);
preorderTraversal(root);
}
}
Python3
# Python implementation of the approach
# Class for the node of the tree
class Node:
def __init__(self, data):
self.data = data
self.children = []
# Function to replace node with
# sum of its left subtree, right
# subtree and its sum
def sumReplacementNary(node):
if (node == None):
return 0
# Total children count
total = len(node.children)
# Taking sum of all the nodes
for i in range(0, total):
node.data += sumReplacementNary(node.children[i])
return node.data
def preorderTraversal(node):
if (node == None):
return
# Total children count
total = len(node.children)
# Print the current node's data
print(node.data, end=" ")
# All the children except the last
for i in range(0, total):
preorderTraversal(node.children[i])
# Driver code
# Create the following tree
# 1
# / | \
# 2 3 4
# / \ \
# 5 6 7
root = Node(1)
root.children.append(Node(2))
root.children.append(Node(3))
root.children.append(Node(4))
root.children[0].children.append(Node(5))
root.children[0].children.append(Node(6))
root.children[0].children.append(Node(7))
print("Initial Pre-order Traversal: ")
preorderTraversal(root)
print("\n")
print("Final Pre-order Traversal: ")
sumReplacementNary(root)
preorderTraversal(root)
C#
// C# implementation of the approach
using System;
public class GFG{
// Class for the node of the tree
class Node {
public int data;
// List of children
public Node []children;
public int length;
public Node()
{
length = 0;
data = 0;
}
public Node(int n, int data_)
{
children = new Node[n];
length = n;
data = data_;
}
};
// Function to replace node with
// sum of its left subtree, right
// subtree and its sum
static int sumReplacementNary(Node node)
{
if (node == null)
return 0;
// Total children count
int total = node.length;
// Taking sum of all the nodes
for (int i = 0; i < total; i++)
node.data += sumReplacementNary(node.children[i]);
return node.data;
}
static void preorderTraversal(Node node)
{
if (node == null)
return;
// Total children count
int total = node.length;
// Print the current node's data
Console.Write(node.data+ " ");
// All the children except the last
for (int i = 0; i < total - 1; i++)
preorderTraversal(node.children[i]);
// Last child
preorderTraversal(node.children[total - 1]);
}
// Driver code
public static void Main(String[] args)
{
/* Create the following tree
1
/ | \
2 3 4
/ \ \
5 6 7
*/
int N = 3;
Node root = new Node(N, 1);
root.children[0] = new Node(N, 2);
root.children[1] = new Node(N, 3);
root.children[2] = new Node(N, 4);
root.children[0].children[0] = new Node(N, 5);
root.children[0].children[1] = new Node(N, 6);
root.children[0].children[2] = new Node(N, 7);
Console.Write("Initial Pre-order Traversal: ");
preorderTraversal(root);
Console.WriteLine();
Console.Write("Final Pre-order Traversal: ");
sumReplacementNary(root);
preorderTraversal(root);
}
}
Javascript
Initial Pre-order Traversal: 1 2 5 6 7 3 4
Final Pre-order Traversal: 28 20 5 6 7 3 4
时间复杂度: O(N),其中 N 是树中的节点数。