📜  二叉树的所有垂直级别的总和

📅  最后修改于: 2021-04-17 14:46:18             🧑  作者: Mango

给定一个由10组成的二进制树作为其节点值,任务是查找二进制树的所有垂直级别的总和,并将每个值都视为二进制表示形式。

例子:

方法:请按照以下步骤解决问题:

  1. 在跟踪到根节点的水平和垂直距离的同时执行树遍历
  2. 将对应于其水平距离的节点值存储在Hashmap中。
  3. 初始化一个变量,例如ans ,以存储所需的结果。
  4. 创建一个Hashmap,例如M ,以存储水平距离作为键和成对的数组{node value,节点到根的距离}
  5. 还需要存储每个节点的高度,因为需要垂直级别按排序顺序(从上到下),以获取其二进制表示形式的正确十进制值。
  6. 执行预遍历树遍历,还传递垂直高度和水平距离作为参数。
    • 如果根不为NULL,请执行以下操作:
      • 将对{节点值,水平距离的垂直高度}附加到M中
      • 遍历左子树,将水平距离减少1
      • 遍历右子树,将水平距离增加1
      • 两个递归调用的垂直高度都增加1
  7. 现在,遍历Hashmap,说M,然后对每个键执行以下步骤:
    • 根据从根节点到它们的高度对值进行排序,然后将获得的二进制数转换为等效的十进制数,并将其存储在变量中,例如B。
    • B的值加到ans
  8. 打印ans的值

下面是上述方法的实现:

C++
// C++ program for super ugly number
#include
using namespace std;
 
// Structure of a Tree node
struct TreeNode
{
  int val = 0;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x)
  {
    val = x;
    left = right = NULL;
  }
};
 
// Function to convert
// binary number to decimal
int getDecimal(vector > arr)
{
 
  // Sort the array on
  // the basis of the
  // first index i.e, height
  sort(arr.begin(), arr.end());
 
  // Store the required
  // decimal equivalent
  // of the number
  int ans = 0;
 
  // Traverse the array
  for (int i = 0; i < arr.size(); i++)
  {
    ans <<= 1;
    ans |= arr[i].second;
  }
 
  // Return the answer
  return ans;
}
 
// Function to traverse the tree
void Traverse(TreeNode *root, int hd, int ht,
              map > > &mp)
{
 
  // If root is NULL, return
  if (!root)
    return;
  mp[hd].push_back({ht, root->val});
 
  // Make recursive calls to the left and
  // right subtree
  Traverse(root->left, hd - 1, ht + 1, mp);
  Traverse(root->right, hd + 1, ht + 1, mp);
}
 
// Function to calculate
// sum of vertical levels
// of a Binary Tree
void getSum(TreeNode *root)
{
 
  // Dictionary to store the
  // vertical level as key and
  // its corresponing
  // binary number as value
  map > > mp;
 
  // Function Call to perform traverse the tree
  Traverse(root, 0, 0, mp);
 
  // Store the required answer
  int ans = 0;
 
  // Get decimal values for each vertical level
  // and add it to ans
  for (auto i:mp)
    ans += getDecimal(i.second);
 
  // Print the answer
  cout<<(ans);
}
 
/* Driver program to test above functions */
int main()
{
 
  TreeNode *root = new TreeNode(1);
  root->left = new TreeNode(1);
  root->right = new TreeNode(0);
  root->left->left = new TreeNode(1);
  root->left->right = new TreeNode(0);
  root->right->left = new TreeNode(1);
  root->right->right = new TreeNode(0);
 
  // Function call to get the
  // sum of vertical level
  // of the tree
  getSum(root);
 
  return 0;
}
 
// This code is contriuted by mohit kumar 29.


Java
// Java program for super ugly number
import java.io.*;
import java.util.*;
 
// Structure of a Tree node
class TreeNode
{
  int val = 0;
  TreeNode left;
  TreeNode right;
 
  TreeNode(int x)
  {
    val = x;
    left = right = null;
  }
}
 
class GFG {
 
  static Map>> mp = new HashMap>>();
 
  // Function to convert
  // binary number to decimal
  static int getDecimal(ArrayList > arr)
  {
 
    // Sort the array on
    // the basis of the
    // first index i.e, height
    Collections.sort(arr, new Comparator>() {   
      @Override
      public int compare(ArrayList o1, ArrayList o2) {
        return o1.get(0).compareTo(o2.get(0));
      }              
    });
 
    // Store the required
    // decimal equivalent
    // of the number
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < arr.size(); i++)
    {
      ans <<= 1;
      ans |= arr.get(i).get(1);
    }
 
    // Return the answer
    return ans;
  }
 
  // Function to traverse the tree
  static void Traverse(TreeNode root, int hd, int ht)
  {
 
    // If root is NULL, return
    if (root == null)
      return;
 
    if(mp.containsKey(hd))
    {
      mp.get(hd).add(new ArrayList(Arrays.asList(ht, root.val)));
    }
    else
    {
      mp.put(hd,new ArrayList>());
      mp.get(hd).add(new ArrayList(Arrays.asList(ht, root.val)));
    }
 
    // Make recursive calls to the left and
    // right subtree
    Traverse(root.left, hd - 1, ht + 1);
    Traverse(root.right, hd + 1, ht + 1);
  }
 
  // Function to calculate
  // sum of vertical levels
  // of a Binary Tree
  static void getSum(TreeNode root)
  {
 
    // Function Call to perform traverse the tree
    Traverse(root, 0, 0);
 
    // Store the required answer
    int ans = 0;
 
    // Get decimal values for each vertical level
    // and add it to ans
    for(Integer key : mp.keySet())
    {
      ans += getDecimal(mp.get(key));
    }
 
    // Print the answer
    System.out.print(ans);
  }
 
  // Driver code
  public static void main (String[] args)
  {
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(1);
    root.right = new TreeNode(0);
    root.left.left = new TreeNode(1);
    root.left.right = new TreeNode(0);
    root.right.left = new TreeNode(1);
    root.right.right = new TreeNode(0);
 
    // Function call to get the
    // sum of vertical level
    // of the tree
    getSum(root);
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python program
# for the above approach
 
# Structure of a Tree node
class TreeNode:
    def __init__(self, val ='',
                 left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to convert
# binary number to decimal
def getDecimal(arr):
 
    # Sort the array on
    # the basis of the
    # first index i.e, height
    arr.sort()
 
    # Store the required
    # decimal equivalent
    # of the number
    ans = 0
 
    # Traverse the array
    for i in range(len(arr)):
        ans <<= 1
        ans |= arr[i][1]
 
    # Return the answer
    return ans
 
# Function to calculate
# sum of vertical levels
# of a Binary Tree
def getSum(root):
 
    # Dictionary to store the
    # vertical level as key and
    # its corresponing
    # binary number as value
    mp = {}
 
    # Function to traverse the tree
    def Traverse(root, hd, ht):
 
        # If root is NULL, return
        if not root:
            return
 
        # Store the value in the map
        if hd not in mp:
            mp[hd] = [[ht, root.val]]
        else:
            mp[hd].append([ht, root.val])
 
        # Make recursive calls to the left and
        # right subtree
        Traverse(root.left, hd - 1, ht + 1)
        Traverse(root.right, hd + 1, ht + 1)
 
    # Function Call to perform traverse the tree
    Traverse(root, 0, 0)
 
    # Store the required answer
    ans = 0
 
    # Get decimal values for each vertical level
    # and add it to ans
    for i in mp:
        ans += getDecimal(mp[i])
 
    # Print the answer
    print(ans)
 
 
# Driver Code
 
# Given Tree
root = TreeNode(1)
root.left = TreeNode(1)
root.right = TreeNode(0)
root.left.left = TreeNode(1)
root.left.right = TreeNode(0)
root.right.left = TreeNode(1)
root.right.right = TreeNode(0)
 
# Function call to get the
# sum of vertical level
# of the tree
getSum(root)


C#
// C# program for super ugly number
using System;
using System.Linq;
using System.Collections.Generic;
 
// Structure of a Tree node
public class TreeNode
{
  public int val = 0;
  public TreeNode left, right;
 
  public TreeNode(int x)
  {
    val = x;
    left = right = null;
  }
}
 
public class GFG
{
 
  static Dictionary>> mp =
    new Dictionary>>();
 
  // Function to convert
  // binary number to decimal
  static int getDecimal(List > arr)
  {
 
    // Sort the array on
    // the basis of the
    // first index i.e, height
    arr.OrderBy( l => l[0]);
 
    // Store the required
    // decimal equivalent
    // of the number
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < arr.Count; i++)
    {
      ans <<= 1;
      ans |= arr[i][1];
    }
 
    // Return the answer
    return ans;
  }
 
  // Function to traverse the tree
  static void Traverse(TreeNode root, int hd, int ht)
  {
 
    // If root is NULL, return
    if (root == null)
      return;
 
    if(mp.ContainsKey(hd))
    {
      mp[hd].Add(new List(){ht, root.val});
    }
    else
    {
      mp.Add(hd,new List>());
      mp[hd].Add(new List(){ht, root.val});
    }
 
    // Make recursive calls to the left and
    // right subtree
    Traverse(root.left, hd - 1, ht + 1);
    Traverse(root.right, hd + 1, ht + 1);
  }
 
  // Function to calculate
  // sum of vertical levels
  // of a Binary Tree
  static void getSum(TreeNode root)
  {
 
    // Function Call to perform traverse the tree
    Traverse(root, 0, 0);
 
    // Store the required answer
    int ans = 0;
 
    // Get decimal values for each vertical level
    // and add it to ans
    foreach(int key in mp.Keys)
    {
      ans += getDecimal(mp[key]);
    }
 
    // Print the answer
    Console.Write(ans);
  }
 
  // Driver code
  static public void Main ()
  {
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(1);
    root.right = new TreeNode(0);
    root.left.left = new TreeNode(1);
    root.left.right = new TreeNode(0);
    root.right.left = new TreeNode(1);
    root.right.right = new TreeNode(0);
 
    // Function call to get the
    // sum of vertical level
    // of the tree
    getSum(root);
  }
}
 
// This code is contributed by rag2127


输出:
7

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