给定由N 个节点组成的二叉树,任务是将二叉树中的每个节点替换为其前序前驱和前序后继之和。
例子:
Input:
2
/ \
3 4
/ \ / \
6 5 7 8
Output:
3
/ \
8 12
/ \ / \
8 10 12 7
Explanation:
- For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor = 3. Sum = 3.
- For Node 3: Preorder predecessor = 2, preorder successor = 6. Sum = 8.
- For Node 6: Preorder predecessor = 3, preorder successor = 5. Sum = 8.
- For Node 5: Preorder predecessor = 6, preorder successor = 4. Sum = 10.
- For Node 4: Preorder predecessor = 5, preorder successor = 7. Sum = 12.
- For Node 7: Preorder predecessor = 4, preorder successor = 8. Sum = 12.
- For Node 8: Preorder predecessor = 7, preorder successor = 0 (as preorder successor is not present). Sum = 7.
Input:
1
/ \
2 3
Output:
2
/ \
4 2
方法:可以通过将树的前序遍历存储在辅助数组中,然后用前序前驱和前序后继之和替换每个节点来解决给定的问题。请按照以下步骤解决问题:
- 声明一个函数,比如replaceNode(root, A[], idx)对起始索引为i的树执行前序遍历,并执行以下步骤:
- 如果根节点为NULL ,则从函数返回。
- 将当前节点的值替换为V[i – 1] + V[i + 1] ,对于元素V[i] ,值V[i – 1]和V[i + 1]是它的前序和前序分别为继任者。
- 递归调用函数replaceNode(root->left, A[], idx + 1)和replaceNode(root->right, A[], idx + 1) 。
- 初始化一个向量V来存储给定树的前序遍历。
- 将0存储在索引0 处,因为最左侧叶节点的前序前导不存在。
- 对给定的树执行预序遍历并将预序遍历存储在向量V 中。
- 在向量的末尾存储0 ,因为最右边的叶节点的前序后继不存在。
- 调用函数replaceNode(root, A[], 1)用所需的总和替换每个节点。
- 完成上述步骤后,打印修改后的树的前序。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Node of a binary tree
struct Node {
int data;
struct Node *left, *right;
};
// Function to generate a new node
struct Node* getnew(int data)
{
// Allocate node
struct Node* newnode
= (struct Node*)malloc(
sizeof(struct Node));
// Assign the data value
newnode->data = data;
newnode->left = newnode->right = NULL;
return newnode;
}
// Function to store Preorder Traversal
// of the binary tree in the vector V
void StorePreorderTraversal(
struct Node* root, vector& v)
{
// If root is NULL, then return
if (root == NULL)
return;
// Store the root's data in V
v.push_back(root->data);
// Recur on the left subtree
StorePreorderTraversal(
root->left, v);
// Recur on right subtree
StorePreorderTraversal(
root->right, v);
}
// Function to replace each node of a
// Binary Tree with the sum of its
// preorder predecessor and successor
void ReplaceNodeWithSum(struct Node* root,
vector& v,
int& i)
{
// If root does not exist
if (root == NULL)
return;
// Update the data present in the
// root by the sum of its preorder
// predecessor and successor
root->data = v[i - 1] + v[i + 1];
// Increment index 'i'
i++;
// Recur on the left subtree
ReplaceNodeWithSum(root->left,
v, i);
// Recur on the right subtree
ReplaceNodeWithSum(root->right,
v, i);
}
// Utility function to replace each
// node of a binary tree with the
// sum of its preorder predecessor
// and successor
void ReplaceNodeWithSumUtil(
struct Node* root)
{
// If tree is empty, then return
if (root == NULL)
return;
vector v;
// Stores the value of preorder
// predecessor for root node
v.push_back(0);
// Store the preorder
// traversal of the tree in V
StorePreorderTraversal(root, v);
// Store the value of preorder
// successor for rightmost leaf
v.push_back(0);
// Replace each node
// with the required sum
int i = 1;
// Function call to update
// the values of the node
ReplaceNodeWithSum(root, v, i);
}
// Function to print the preorder
// traversal of a binary tree
void PreorderTraversal(
struct Node* root)
{
// If root is NULL
if (root == NULL)
return;
// Print the data of node
cout << root->data << " ";
// Recur on the left subtree
PreorderTraversal(root->left);
// Recur on the right subtree
PreorderTraversal(root->right);
}
// Driver Code
int main()
{
// Binary Tree
struct Node* root = getnew(2);
root->left = getnew(3);
root->right = getnew(4);
root->left->left = getnew(6);
root->left->right = getnew(5);
root->right->left = getnew(7);
root->right->right = getnew(8);
// Print the preorder traversal
// of the original tree
cout << "Preorder Traversal before"
<< " modification of tree: ";
PreorderTraversal(root);
ReplaceNodeWithSumUtil(root);
// Print the preorder traversal
// of the modified tree
cout << "\nPreorder Traversal after "
<< "modification of tree: ";
PreorderTraversal(root);
return 0;
}
Java
// Java program for the above approach
import java.util.Vector;
class GFG{
// Node of a binary tree
static class Node
{
int data;
Node left, right;
}
// INT class
static class INT
{
int data;
}
// Function to get a new node
// of a binary tree
static Node getNode(int data)
{
// Allocate node
Node new_node = new Node();
// Put in the data;
new_node.data = data;
new_node.left = new_node.right = null;
return new_node;
}
// Function to print the preorder traversal
// of a binary tree
static void preorderTraversal(Node root)
{
// If root is null
if (root == null)
return;
// First print the data of node
System.out.print(root.data + " ");
// Then recur on left subtree
preorderTraversal(root.left);
// Now recur on right subtree
preorderTraversal(root.right);
}
// Function to replace each node with the sum of its
// preorder predecessor and successor
static void replaceNodeWithSum(Node root,
Vector V, INT i)
{
// If root is null
if (root == null)
return;
// Replace node's data with the sum of its
// preorder predecessor and successor
root.data = V.get(i.data - 1) +
V.get(i.data + 1);
// Move 'i' to point to the next 'V' element
i.data++;
// First recur on left child
replaceNodeWithSum(root.left, V, i);
// Now recur on right child
replaceNodeWithSum(root.right, V, i);
}
// Function to store the preorder traversal
// of the binary tree in V
static void storePreorderTraversal(Node root,
Vector V)
{
// If root is null
if (root == null)
return;
// Then store the root's data in 'V'
V.add(root.data);
// First recur on left child
storePreorderTraversal(root.left, V);
// Now recur on right child
storePreorderTraversal(root.right, V);
}
// Utility function to replace each node in binary
// tree with the sum of its preorder predecessor
// and successor
static void replaceNodeWithSumUtil(Node root)
{
// If tree is empty
if (root == null)
return;
Vector V = new Vector();
// Store the value of preorder predecessor
// for the leftmost leaf
V.add(0);
// Store the preoder traversal of the tree in V
storePreorderTraversal(root, V);
// Store the value of preorder successor
// for the rightmost leaf
V.add(0);
// Replace each node with the required sum
INT i = new INT();
i.data = 1;
replaceNodeWithSum(root, V, i);
}
// Driver code
public static void main(String[] args)
{
// Binary tree formation
Node root = getNode(2);
root.left = getNode(3);
root.right = getNode(4);
root.left.left = getNode(6);
root.left.right = getNode(5);
root.right.left = getNode(7);
root.right.right = getNode(8);
// Print the preorder traversal of the original tree
System.out.print("Preorder Transversal before " +
"modification of tree:\n");
preorderTraversal(root);
replaceNodeWithSumUtil(root);
// Print the preorder traversal of the modification
// tree
System.out.print("\nPreorder Transversal after " +
"modification of tree:\n");
preorderTraversal(root);
}
}
// This code is contributed by abhinavjain194
Python3
# Python3 program for the above approach
# Node of a binary tree
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function to store Preorder Traversal
# of the binary tree in the vector V
def StorePreorderTraversal(root):
global v
# If root is NULL, then return
if (root == None):
return
# Store the root's data in V
v.append(root.data)
# Recur on the left subtree
StorePreorderTraversal(root.left)
# Recur on right subtree
StorePreorderTraversal(root.right)
# Function to replace each node of a
# Binary Tree with the sum of its
# preorder predecessor and successor
def ReplaceNodeWithSum(root):
global v, i
# If root does not exist
if (root == None):
return
# Update the data present in the
# root by the sum of its preorder
# predecessor and successor
root.data = v[i - 1] + v[i + 1]
# Increment index 'i'
i += 1
# Recur on the left subtree
ReplaceNodeWithSum(root.left)
# Recur on the right subtree
ReplaceNodeWithSum(root.right)
# Utility function to replace each
# node of a binary tree with the
# sum of its preorder predecessor
# and successor
def ReplaceNodeWithSumUtil(root):
global v, i
# If tree is empty, then return
if (root == None):
return
v.clear()
# Stores the value of preorder
# predecessor for root node
v.append(0)
# Store the preorder
# traversal of the tree in V
StorePreorderTraversal(root)
# Store the value of preorder
# successor for rightmost leaf
v.append(0)
# Replace each node
# with the required sum
i = 1
# Function call to update
# the values of the node
ReplaceNodeWithSum(root)
# Function to print the preorder
# traversal of a binary tree
def PreorderTraversal(root):
# If root is NULL
if (root == None):
return
# Print the data of node
print(root.data, end = " ")
# Recur on the left subtree
PreorderTraversal(root.left)
# Recur on the right subtree
PreorderTraversal(root.right)
# Driver Code
if __name__ == '__main__':
# Binary Tree
v, i = [], 0
root = Node(2)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(6)
root.left.right = Node(5)
root.right.left = Node(7)
root.right.right = Node(8)
# Print the preorder traversal
# of the original tree
print("Preorder Traversal before "
"modification of tree: ", end = "")
PreorderTraversal(root)
ReplaceNodeWithSumUtil(root)
# Print the preorder traversal
# of the modified tree
print("\nPreorder Traversal after "
"modification of tree: ", end = "")
PreorderTraversal(root)
# This code is contributed by mohit kumar 29
Preorder Traversal before modification of tree: 2 3 6 5 4 7 8
Preorder Traversal after modification of tree: 3 8 8 10 12 12 7
时间复杂度: O(N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live