将二叉树中的每个节点替换为其前导和后继的总和
给定一棵包含n 个节点的二叉树。问题是用它的有序前驱和有序后继之和替换二叉树中的每个节点。
例子:
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
Output : 11
/ \
9 13
/ \ / \
2 3 4 3
For 1:
Inorder predecessor = 5
Inorder successor = 6
Sum = 11
For 4:
Inorder predecessor = 0
(as inorder predecessor is not present)
Inorder successor = 2
Sum = 2
For 7:
Inorder predecessor = 3
Inorder successor = 0
(as inorder successor is not present)
Sum = 3
方法:创建一个数组arr 。在索引0处存储 0。现在,将树的中序遍历存储在数组arr中。然后,在最后一个索引处存储0 。 0被存储为最左边叶子的有序前驱,而最右边叶子的有序后继不存在。现在,执行中序遍历并在遍历节点时用arr[i-1] + arr[i+1]替换节点的值,然后递增i 。在开始时初始化i = 1。对于元素arr[i] ,值arr[i-1]和arr[i+1]分别是它的有序前驱和有序后继。
C++
// C++ implementation to replace each node
// in binary tree with the sum of its inorder
// predecessor and successor
#include
using namespace std;
// node of a binary tree
struct Node {
int data;
struct Node* left, *right;
};
// function to get a new node of a binary tree
struct Node* getNode(int data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data;
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}
// function to store the inorder traversal
// of the binary tree in 'arr'
void storeInorderTraversal(struct Node* root,
vector& arr)
{
// if root is NULL
if (!root)
return;
// first recur on left child
storeInorderTraversal(root->left, arr);
// then store the root's data in 'arr'
arr.push_back(root->data);
// now recur on right child
storeInorderTraversal(root->right, arr);
}
// function to replace each node with the sum of its
// inorder predecessor and successor
void replaceNodeWithSum(struct Node* root,
vector arr, int* i)
{
// if root is NULL
if (!root)
return;
// first recur on left child
replaceNodeWithSum(root->left, arr, i);
// replace node's data with the sum of its
// inorder predecessor and successor
root->data = arr[*i - 1] + arr[*i + 1];
// move 'i' to point to the next 'arr' element
++*i;
// now recur on right child
replaceNodeWithSum(root->right, arr, i);
}
// Utility function to replace each node in binary
// tree with the sum of its inorder predecessor
// and successor
void replaceNodeWithSumUtil(struct Node* root)
{
// if tree is empty
if (!root)
return;
vector arr;
// store the value of inorder predecessor
// for the leftmost leaf
arr.push_back(0);
// store the inorder traversal of the tree in 'arr'
storeInorderTraversal(root, arr);
// store the value of inorder successor
// for the rightmost leaf
arr.push_back(0);
// replace each node with the required sum
int i = 1;
replaceNodeWithSum(root, arr, &i);
}
// function to print the preorder traversal
// of a binary tree
void preorderTraversal(struct Node* root)
{
// if root is NULL
if (!root)
return;
// first print the data of node
cout << root->data << " ";
// then recur on left subtree
preorderTraversal(root->left);
// now recur on right subtree
preorderTraversal(root->right);
}
// Driver program to test above
int main()
{
// binary tree formation
struct Node* root = getNode(1); /* 1 */
root->left = getNode(2); /* / \ */
root->right = getNode(3); /* 2 3 */
root->left->left = getNode(4); /* / \ / \ */
root->left->right = getNode(5); /* 4 5 6 7 */
root->right->left = getNode(6);
root->right->right = getNode(7);
cout << "Preorder Traversal before tree modification:n";
preorderTraversal(root);
replaceNodeWithSumUtil(root);
cout << "\nPreorder Traversal after tree modification:n";
preorderTraversal(root);
return 0;
}
Java
// Java implementation to replace each node
// in binary tree with the sum of its inorder
// predecessor and successor
import java.util.*;
class Solution
{
// 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 store the inorder traversal
// of the binary tree in 'arr'
static void storeInorderTraversal( Node root,
Vector arr)
{
// if root is null
if (root==null)
return;
// first recur on left child
storeInorderTraversal(root.left, arr);
// then store the root's data in 'arr'
arr.add(root.data);
// now recur on right child
storeInorderTraversal(root.right, arr);
}
// function to replace each node with the sum of its
// inorder predecessor and successor
static void replaceNodeWithSum( Node root,
Vector arr, INT i)
{
// if root is null
if (root==null)
return;
// first recur on left child
replaceNodeWithSum(root.left, arr, i);
// replace node's data with the sum of its
// inorder predecessor and successor
root.data = arr.get(i.data - 1) + arr.get(i.data + 1);
// move 'i' to point to the next 'arr' element
i.data++;
// now recur on right child
replaceNodeWithSum(root.right, arr, i);
}
// Utility function to replace each node in binary
// tree with the sum of its inorder predecessor
// and successor
static void replaceNodeWithSumUtil( Node root)
{
// if tree is empty
if (root==null)
return;
Vector arr= new Vector();
// store the value of inorder predecessor
// for the leftmost leaf
arr.add(0);
// store the inorder traversal of the tree in 'arr'
storeInorderTraversal(root, arr);
// store the value of inorder successor
// for the rightmost leaf
arr.add(0);
// replace each node with the required sum
INT i = new INT();
i.data=1;
replaceNodeWithSum(root, arr, i);
}
// 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);
}
// Driver program to test above
public static void main(String args[])
{
// binary tree formation
Node root = getNode(1); // 1
root.left = getNode(2); // / \
root.right = getNode(3); // 2 3
root.left.left = getNode(4); // / \ / \
root.left.right = getNode(5); // 4 5 6 7
root.right.left = getNode(6);
root.right.right = getNode(7);
System.out.println( "Preorder Traversal before tree modification:");
preorderTraversal(root);
replaceNodeWithSumUtil(root);
System.out.println("\nPreorder Traversal after tree modification:");
preorderTraversal(root);
}
}
//contributed by Arnab Kundu
Python3
# Python3 implementation to replace each
# node in binary tree with the sum of its
# inorder predecessor and successor
# class to get a new node of a
# binary tree
class getNode:
def __init__(self, data):
# put in the data
self.data = data
self.left = self.right = None
# function to store the inorder traversal
# of the binary tree in 'arr'
def storeInorderTraversal(root, arr):
# if root is None
if (not root):
return
# first recur on left child
storeInorderTraversal(root.left, arr)
# then store the root's data in 'arr'
arr.append(root.data)
# now recur on right child
storeInorderTraversal(root.right, arr)
# function to replace each node with the
# sum of its inorder predecessor and successor
def replaceNodeWithSum(root, arr, i):
# if root is None
if (not root):
return
# first recur on left child
replaceNodeWithSum(root.left, arr, i)
# replace node's data with the sum of its
# inorder predecessor and successor
root.data = arr[i[0] - 1] + arr[i[0] + 1]
# move 'i' to point to the next 'arr' element
i[0] += 1
# now recur on right child
replaceNodeWithSum(root.right, arr, i)
# Utility function to replace each node in
# binary tree with the sum of its inorder
# predecessor and successor
def replaceNodeWithSumUtil(root):
# if tree is empty
if (not root):
return
arr = []
# store the value of inorder predecessor
# for the leftmost leaf
arr.append(0)
# store the inorder traversal of the
# tree in 'arr'
storeInorderTraversal(root, arr)
# store the value of inorder successor
# for the rightmost leaf
arr.append(0)
# replace each node with the required sum
i = [1]
replaceNodeWithSum(root, arr, i)
# function to print the preorder traversal
# of a binary tree
def preorderTraversal(root):
# if root is None
if (not root):
return
# first print the data of node
print(root.data, end = " ")
# then recur on left subtree
preorderTraversal(root.left)
# now recur on right subtree
preorderTraversal(root.right)
# Driver Code
if __name__ == '__main__':
# binary tree formation
root = getNode(1) # 1
root.left = getNode(2) # / \
root.right = getNode(3) # 2 3
root.left.left = getNode(4) # / \ / \
root.left.right = getNode(5) # 4 5 6 7
root.right.left = getNode(6)
root.right.right = getNode(7)
print("Preorder Traversal before",
"tree modification:")
preorderTraversal(root)
replaceNodeWithSumUtil(root)
print()
print("Preorder Traversal after",
"tree modification:")
preorderTraversal(root)
# This code is contributed by PranchalK
C#
// C# implementation to replace each
// node in binary tree with the sum
// of its inorder predecessor and successor
using System;
using System.Collections.Generic;
class GFG
{
// node of a binary tree
public class Node
{
public int data;
public Node left, right;
}
// INT class
public class INT
{
public int data;
}
// function to get a new node
// of a binary tree
public 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 store the inorder traversal
// of the binary tree in 'arr'
public static void storeInorderTraversal(Node root,
List arr)
{
// if root is null
if (root == null)
{
return;
}
// first recur on left child
storeInorderTraversal(root.left, arr);
// then store the root's data in 'arr'
arr.Add(root.data);
// now recur on right child
storeInorderTraversal(root.right, arr);
}
// function to replace each node with
// the sum of its inorder predecessor
// and successor
public static void replaceNodeWithSum(Node root,
List arr, INT i)
{
// if root is null
if (root == null)
{
return;
}
// first recur on left child
replaceNodeWithSum(root.left, arr, i);
// replace node's data with the
// sum of its inorder predecessor
// and successor
root.data = arr[i.data - 1] + arr[i.data + 1];
// move 'i' to point to the
// next 'arr' element
i.data++;
// now recur on right child
replaceNodeWithSum(root.right, arr, i);
}
// Utility function to replace each
// node in binary tree with the sum
// of its inorder predecessor and successor
public static void replaceNodeWithSumUtil(Node root)
{
// if tree is empty
if (root == null)
{
return;
}
List arr = new List();
// store the value of inorder
// predecessor for the leftmost leaf
arr.Add(0);
// store the inorder traversal
// of the tree in 'arr'
storeInorderTraversal(root, arr);
// store the value of inorder successor
// for the rightmost leaf
arr.Add(0);
// replace each node with
// the required sum
INT i = new INT();
i.data = 1;
replaceNodeWithSum(root, arr, i);
}
// function to print the preorder
// traversal of a binary tree
public static void preorderTraversal(Node root)
{
// if root is null
if (root == null)
{
return;
}
// first print the data of node
Console.Write(root.data + " ");
// then recur on left subtree
preorderTraversal(root.left);
// now recur on right subtree
preorderTraversal(root.right);
}
// Driver Code
public static void Main(string[] args)
{
// binary tree formation
Node root = getNode(1); // 1
root.left = getNode(2); // / \
root.right = getNode(3); // 2 3
root.left.left = getNode(4); // / \ / \
root.left.right = getNode(5); // 4 5 6 7
root.right.left = getNode(6);
root.right.right = getNode(7);
Console.WriteLine("Preorder Traversal " +
"before tree modification:");
preorderTraversal(root);
replaceNodeWithSumUtil(root);
Console.WriteLine("\nPreorder Traversal after " +
"tree modification:");
preorderTraversal(root);
}
}
// This code is contributed by Shrikant13
Javascript
输出:
Preorder Traversal before tree modification:
1 2 4 5 3 6 7
Preorder Traversal after tree modification:
11 9 2 3 13 4 3
时间复杂度: O(n)
辅助空间: O(n)