📜  将二叉树对角压缩成整数

📅  最后修改于: 2021-10-27 08:22:06             🧑  作者: Mango

给定一个由N 个节点组成的二叉树,任务是首先对角压缩树以获取整数列表,然后使用以下操作再次压缩列表以获取单个整数:

  • 当一棵树被对角压缩时,它的二进制表示值被压缩。
  • 考虑对角线上存在的每个节点值的每个位位置。如果一个位置有S设置位和NS未设置位,则仅当S大于NS时才设置该位置的位。否则,取消设置该位置的位。
  • 压缩每个对角线以将树转换为列表。然后,使用相同的过程将每个数组元素压缩为单个整数。

例子:

方法:这个想法是使用 Hashmap 来存储属于树的特定对角线的所有节点。请按照以下步骤解决问题:

  • 对于树的对角遍历,跟踪每个节点到根节点的水平距离。
  • 使用 Hashmap 来存储属于同一对角线的元素。
  • 遍历后,对树的每个对角线的每个位置计算设置位的数量,并为设置位数量超过未设置位数量的位置设置位。
  • 将每个对角线的压缩值存储在一个数组中。
  • 获得数组后,应用相同的步骤进行压缩以获得所需的整数。

下面是上述方法的实现:

C++
#include 
 
using namespace std;
 
struct TreeNode{
  int val;
  TreeNode *left,*right;
 
    TreeNode(int v){
        val = v;
        left = NULL;
        right = NULL;
    }
};
 
// Function to compress the elements
// in an array into an integer
int findCompressValue(vector arr){
    int ans = 0;
    int getBit = 1;
 
    // Check for each bit position
    for (int i = 0; i < 32; i++){
        int S = 0;
        int NS = 0;
 
        for (int j:arr){
 
            // Update the count of
            // set and non-set bits
            if (getBit & j)
                S += 1;
            else
                NS += 1;
          }
 
        // If number of set bits exceeds
        // the number of non-set bits,
        // then add set bits value to ans
        if (S > NS)
            ans += pow(2,i);
 
        getBit <<= 1;
      }
    return ans;
}
 
// Perform Inorder Traversal
// on the Binary Tree
void diagonalOrder(TreeNode *root,int d,map > &mp){
    if (!root)
        return;
 
    // Store all nodes of the same
    // line together as a vector
    mp[d].push_back(root->val);
 
    // Increase the vertical
    // distance of left child
    diagonalOrder(root->left, d + 1, mp);
 
    // Vertical distance remains
    // same for right child
    diagonalOrder(root->right, d, mp);
}
 
// Function to compress a given
// Binary Tree into an integer
int findInteger(TreeNode *root){
 
    // Declare a map
    map > mp;
 
    diagonalOrder(root, 0, mp);
 
    //Store all the compressed values of
    //diagonal elements in an array
    vector arr;
 
    for (auto i:mp)
        arr.push_back(findCompressValue(i.second));
 
    // Compress the array into an integer
    return findCompressValue(arr);
}
 
// Driver Code
// Given Input
int main()
{
  TreeNode *root = new TreeNode(6);
  root->left = new TreeNode(5);
  root->right = new TreeNode(3);
  root->left->left = new TreeNode(3);
  root->left->right = new TreeNode(5);
  root->right->left = new TreeNode(3);
  root->right->right = new TreeNode(4);
 
  // Function Call
  cout << findInteger(root);
 
  return 0;
}
 
// This code is contributed by mohit kumar 29.


Python3
# Python program for the above approach
 
class TreeNode:
 
    def __init__(self, val ='',
                 left = None,
                 right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to compress the elements
# in an array into an integer
def findCompressValue(arr):
    ans = 0
    getBit = 1
 
    # Check for each bit position
    for i in range(32):
        S = 0
        NS = 0
 
        for j in arr:
 
            # Update the count of
            # set and non-set bits
            if getBit & j:
                S += 1
            else:
                NS += 1
 
        # If number of set bits exceeds
        # the number of non-set bits,
        # then add set bits value to ans
        if S > NS:
            ans += 2**i
 
        getBit <<= 1
 
    return ans
 
# Function to compress a given
# Binary Tree into an integer
def findInteger(root):
 
    # Declare a map
    mp = {}
 
    # Perform Inorder Traversal
    # on the Binary Tree
    def diagonalOrder(root, d, mp):
        if not root:
            return
 
        # Store all nodes of the same
        # line together as a vector
        try:
            mp[d].append(root.val)
 
        except KeyError:
            mp[d] = [root.val]
 
        # Increase the vertical
        # distance of left child
        diagonalOrder(root.left, d + 1, mp)
 
        # Vertical distance remains
        # same for right child
        diagonalOrder(root.right, d, mp)
 
    diagonalOrder(root, 0, mp)
 
    # Store all the compressed values of
    # diagonal elements in an array
    arr = []
    for i in mp:
        arr.append(findCompressValue(mp[i]))
 
    # Compress the array into an integer
    return findCompressValue(arr)
 
 
# Driver Code
# Given Input
root = TreeNode(6)
root.left = TreeNode(5)
root.right = TreeNode(3)
root.left.left = TreeNode(3)
root.left.right = TreeNode(5)
root.right.left = TreeNode(3)
root.right.right = TreeNode(4)
 
# Function Call
print(findInteger(root))


输出:
7

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。