📌  相关文章
📜  具有XOR值K的二叉树中的子树计数

📅  最后修改于: 2021-05-05 03:06:24             🧑  作者: Mango

给定一个值K和一个二叉树,任务是找出所有元素的XOR等于K子树的数量。
例子:

Input  K = 5, Tree =
       2
      / \
     1   9
    / \
   10  5
Output: 2
Explanation:
Subtree 1: 
       5
It has only one element i.e. 5.
So XOR of subtree = 5
Subtree 1: 
       2
      / \
     1   9
    / \
   10  5
It has elements 2, 1, 9, 10, 5.
So XOR of subtree = 2 ^ 1 ^ 9 ^ 10 ^ 5 = 5

Input  K = 3, Tree =
       4
      / \
     3   9
    / \
   2   2
Output: 1
Explanation
Subtree:
     3
    / \
   2   2
It has elements 3, 2, 2.
So XOR of subtree = 3 ^ 2 ^ 2 = 3

方法

  1. 使用预遍历递归遍历树。
  2. 对于每个节点,请继续按以下公式计算其子树的XOR:
  1. 如果任何子树的XOR为K,则递增计数器变量。
  2. 将计数器中的值打印为所需的计数

下面是上述方法的实现:

C++
// C++ program to find the count of
// subtrees in a Binary Tree
// having XOR value K
 
#include 
using namespace std;
 
// A binary tree node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// A utility function to
// allocate a new node
struct Node* newNode(int data)
{
    struct Node* newNode = new Node;
    newNode->data = data;
    newNode->left
        = newNode->right = NULL;
    return (newNode);
}
 
int rec(Node* root, int& res, int& k)
{
    // Base Case:
    // If node is NULL, return 0
    if (root == NULL) {
        return 0;
    }
 
    // Calculating the XOR
    // of the current subtree
    int xr = root->data;
    xr ^= rec(root->left, res, k);
    xr ^= rec(root->right, res, k);
 
    // Increment res
    // if xr is equal to k
    if (xr == k) {
        res++;
    }
 
    // Return the XOR value
    // of the current subtree
    return xr;
}
 
// Function to find the required count
int findCount(Node* root, int K)
{
    // Initialize result variable 'res'
    int res = 0;
 
    // Recursively traverse the tree
    // and compute the count
    rec(root, res, K);
 
    // return the count 'res'
    return res;
}
 
// Driver program
int main(void)
{
 
    /*
        2
       / \
      1   9
     / \
    10  5
    */
 
    // Create the binary tree
    // by adding nodes to it
    struct Node* root = newNode(2);
    root->left = newNode(1);
    root->right = newNode(9);
    root->left->left = newNode(10);
    root->left->right = newNode(5);
 
    int K = 5;
 
    cout << findCount(root, K);
    return 0;
}


Java
// Java program to find the count of
// subtrees in a Binary Tree
// having XOR value K
import java.util.*;
 
class GFG{
 
    // A binary tree node
    static class Node
    {
        int data;
        Node left,right;
    };
    static int res;
    static int k;
 
    // A utility function to
    // allocate a new node
    static Node newNode(int data)
    {
        Node newNode = new Node();
        newNode.data = data;
        newNode.left= null;
        newNode.right = null;
        return newNode;
    }
     
    static int rec(Node root)
    {
        // Base Case:
        // If node is null, return 0
        if (root == null) {
            return 0;
        }
     
        // Calculating the XOR
        // of the current subtree
        int xr = (root.data);//^rec(root.left)^rec(root.right);
        xr ^= rec(root.left);
        xr ^= rec(root.right);
         
        // Increment res
        // if xr is equal to k
        if (xr == k) {
            res++;
        }
     
        // Return the XOR value
        // of the current subtree
        return xr;
    }
     
    // Function to find the required count
    static int findCount(Node root, int K)
    {
        // Initialize result variable 'res'
        res = 0;
        k = K;
 
        // Recursively traverse the tree
        // and compute the count
        rec(root);
 
        // return the count 'res'
        return res;
    }
     
    // Driver program
    public static void main(String args[])
    {
     
        /*
            2
        / \
        1 9
        / \
        10 5
        */
     
        // Create the binary tree
        // by adding nodes to it
        Node root = newNode(2);
        root.left = newNode(1);
        root.right = newNode(9);
        root.left.left =newNode(10);
        root.left.right = newNode(5);
     
        int K = 5;
     
        System.out.println(findCount(root, K));   
    }
}
 
 
// This code is contributed by AbhiThakur


Python3
# Python3 program to find the count of
# subtrees in a Binary Tree
# having XOR value K
  
# A binary tree node
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
         
# A utility function to
# allocate a new node
def newNode(data):
     
    newNode = Node(data)
    return newNode
 
def rec(root, res, k):
 
    # Base Case:
    # If node is None, return 0
    if (root == None):
        return [0, res];
  
    # Calculating the XOR
    # of the current subtree
    xr = root.data;
    tmp,res = rec(root.left, res, k);
    xr^=tmp
    tmp,res = rec(root.right, res, k);
    xr^=tmp
  
    # Increment res
    # if xr is equal to k
    if (xr == k):
        res += 1
   
    # Return the XOR value
    # of the current subtree
    return xr, res;
 
# Function to find the required count
def findCount(root, K):
 
    # Initialize result variable 'res'
    res = 0;
  
    # Recursively traverse the tree
    # and compute the count
    tmp,res=rec(root, res, K);
  
    # return the count 'res'
    return res;
 
# Driver program
if __name__=='__main__':
  
    '''
        2
       / \
      1   9
     / \
    10  5
    '''
  
    # Create the binary tree
    # by adding nodes to it
    root = newNode(2);
    root.left = newNode(1);
    root.right = newNode(9);
    root.left.left = newNode(10);
    root.left.right = newNode(5);
  
    K = 5;
  
    print(findCount(root, K))
 
# This code is contributed by rutvik_56


C#
// C# program to find the count of
// subtrees in a Binary Tree
// having XOR value K
using System;
 
public class GFG{
  
    // A binary tree node
    class Node
    {
        public int data;
        public Node left,right;
    };
    static int res;
    static int k;
  
    // A utility function to
    // allocate a new node
    static Node newNode(int data)
    {
        Node newNode = new Node();
        newNode.data = data;
        newNode.left= null;
        newNode.right = null;
        return newNode;
    }
      
    static int rec(Node root)
    {
        // Base Case:
        // If node is null, return 0
        if (root == null) {
            return 0;
        }
      
        // Calculating the XOR
        // of the current subtree
        int xr = (root.data);//^rec(root.left)^rec(root.right);
        xr ^= rec(root.left);
        xr ^= rec(root.right);
          
        // Increment res
        // if xr is equal to k
        if (xr == k) {
            res++;
        }
      
        // Return the XOR value
        // of the current subtree
        return xr;
    }
      
    // Function to find the required count
    static int findCount(Node root, int K)
    {
        // Initialize result variable 'res'
        res = 0;
        k = K;
  
        // Recursively traverse the tree
        // and compute the count
        rec(root);
  
        // return the count 'res'
        return res;
    }
      
    // Driver program
    public static void Main(String []args)
    {
      
        /*
            2
        / \
        1 9
        / \
        10 5
        */
      
        // Create the binary tree
        // by adding nodes to it
        Node root = newNode(2);
        root.left = newNode(1);
        root.right = newNode(9);
        root.left.left =newNode(10);
        root.left.right = newNode(5);
      
        int K = 5;
      
        Console.WriteLine(findCount(root, K));   
    }
}
  
// This code is contributed by sapnasingh4991


输出:
2

性能分析:
时间复杂度:与上述方法一样,我们仅对每个节点进行一次迭代,因此将花费O(N)时间,其中N是二叉树中的节点数。
辅助空间复杂度:与上述方法一样,没有使用额外的空间,因此辅助空间复杂度将为O(1)