将给定的二叉树转换为 XOR 树
给定一棵二叉树,其中每个节点的值都是0或1,任务是将给定的二叉树转换为XOR 树,即每个节点值都是其子节点之间的逻辑 XOR 的树。
注意:不考虑叶子节点和具有一个孩子的节点,因为它们没有两个孩子。
例子:
Input:
1
/ \
1 0
/ \ / \
0 1 0 1
Output:
0
/ \
1 1
/ \ / \
0 1 0 1
Explanation: Each node value is the Logical XOR of its children.
For example, the right most node in 2nd level is the Logical XOR of its children. i.e., 0 ^ 1 = 1
Input:
1
/ \
0 0
/ \ /
1 0 1
Output:
1
/ \
1 0
/ \ /
1 0 1
Explanation: Each node has value same as the Logical XOR of its children.
For example, the left most node in 2nd level is the Logical Xor of its children. i.e., 1 ^ 0 = 1.
The rightmost child of second level has value unchanged because it has only one child.
方法:可以根据以下思路解决问题:
The idea is to perform a postorder traversal of the tree because in postorder traversal both the children are visited before the root node. During the traversal keep on performing the XOR of the children and change the value of the current node as per that.
请按照以下步骤解决问题:
- 对于每个节点,递归地检查节点的子节点。
- 如果节点只有一个孩子或没有孩子,那么什么也不做。
- 否则,如果节点有两个子节点,则只需使用其子节点的逻辑 XOR 更新节点的数据。
下面是上述方法的实现:
C++
// C++ program to convert a BT to XOR tree
#include
using namespace std;
// Struct node of binary tree
struct Node {
int data;
Node *left, *right;
};
// Function to create a new node
Node* newNode(int key)
{
Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
// Utility function that converts
// BT to XOR tree which holds
// logical XOR property.
void convertTree(Node* root)
{
// Base case
if (root == NULL)
return;
// Recursion for left subtree
convertTree(root->left);
// Recursion for right subtree
convertTree(root->right);
// If the node has both childrens
// then update node's data as
// Logical Xor between childrens.
if (root->left != NULL
&& root->right != NULL)
root->data = root->left->data
^ root->right->data;
}
// Function to print
void printInorder(Node* root)
{
if (root == NULL)
return;
// Recursion for left subtree
printInorder(root->left);
// Print the data
cout << root->data << " ";
// Now recursion for right subtree
printInorder(root->right);
}
// Driver code
int main()
{
// Create a binary tree
Node* root = newNode(1);
root->left = newNode(1);
root->right = newNode(0);
root->left->left = newNode(0);
root->left->right = newNode(1);
root->right->left = newNode(0);
root->right->right = newNode(1);
cout << "Before conversion: ";
printInorder(root);
// Function to convert the tree
convertTree(root);
cout << "\nAfter conversion: ";
printInorder(root);
return 0;
}
Javascript
Before conversion: 0 1 1 1 0 0 1
After conversion: 0 1 1 0 0 1 1
时间复杂度:O(N)
辅助空间:O(N)