📌  相关文章
📜  二叉树所有垂直层次的总和

📅  最后修改于: 2021-09-06 06:22:56             🧑  作者: Mango

给定一棵由10作为其节点值的二叉树,任务是找到二叉树所有垂直级别的总和,将每个值视为一个二元表示。

例子:

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

  1. 在跟踪与根节点的水平和垂直距离的同时执行树遍历
  2. 将其水平距离对应的节点值存储在一个 Hashmap 中。
  3. 初始化一个变量,比如ans ,以存储所需的结果。
  4. 创建一个哈希图,比如M ,将水平距离存储为键和一组对{node value, distance of the node from the root}
  5. 每个节点的高度也存储为垂直级别需要按排序顺序(从上到下),以获得其二进制表示的正确十进制值。
  6. 执行预序树遍历并将垂直高度和水平距离作为参数传递。
    • 如果root不为NULL,执行以下操作:
      • M 中追加{node value, vertical height in the horizontal distance}对。
      • 遍历左子树,将水平距离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)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live