📌  相关文章
📜  生成一个表示二叉树每个垂直级别节点的 GCD 的数组

📅  最后修改于: 2021-10-28 01:32:45             🧑  作者: Mango

给定一棵二叉树,任务是构造一个数组,使得数组的i索引包含存在于给定二叉树的i垂直级别的所有节点的 GCD。

例子:

方法:可以通过执行给定树的垂直顺序遍历来解决给定的问题,并存储出现在相同垂直线上的每个节点的值,然后打印为每个级别存储的所有值的 GCD。请按照以下步骤解决此问题:

  • 初始化一个 Map M来存储执行遍历时每条垂直线的所有节点的 GCD。
  • 初始化一个变量,比如hd0以跟踪水平距离。
  • 递归遍历给定的树并执行以下步骤:
    • 将当前节点的值存储在映射M 中作为作为hd作为节点的值
    • 将变量hd1并递归调用左子树。
    • 将变量hd增加1并递归调用右子树。
  • 遍历地图,以每个水平距离找到地图中存储的所有节点的GCD作为key,打印得到的GCD值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Class for node of binary tree
struct TreeNode
{
    int val;
    TreeNode *left, *right;
     
    TreeNode(int x)
    {
        val = x;
        left = right = NULL;
    }
};
 
// Function to find GCD of two numbers
int GCD(int a, int b)
{
    if (!b)
        return a;
         
    // Recursively find the GCD
    return GCD(b, a % b);
}
 
// Stores the element for each
// vertical distance
unordered_map mp;
 
// Function to traverse the tree
void Trav(TreeNode *root, int hd)
{
    if (!root)
        return;
 
    // Store the values in the map
    if (mp[hd] == 0)
        mp[hd] = root->val;
    else
        mp[hd] = GCD(mp[hd], root->val);
 
    // Recursive Calls
    Trav(root->left, hd - 1);
    Trav(root->right, hd + 1);
}
 
// Function to construct array from
// vertically positioned nodes
void constructArray(TreeNode *root)
{
    Trav(root, 0);
     
    // Get range of horizontal distances
    int lower = INT_MAX, upper = 0;
    for(auto it:mp)
    {
        lower = min(lower, it.first);
        upper = max(upper, it.first);
    }
     
    vector ans;
     
    // Extract the array of values
    for(int i = lower; i < upper + 1; i++)
        ans.push_back(mp[i]);
     
    // Print the constructed array
    cout << "[";
    for(int i = 0; i < ans.size() - 1; i++)
        cout << ans[i] << ", ";
         
    cout << ans[ans.size() - 1] << "]";
}
 
// Driver code
int main()
{
    TreeNode *root = new TreeNode(5);
    root->left = new TreeNode(4);
    root->right = new TreeNode(7);
    root->left->left = new TreeNode(8);
    root->left->left->right = new TreeNode(8);
    root->left->right = new TreeNode(10);
    root->right->right = new TreeNode(6);
     
    // Function Call
    constructArray(root);
     
    return 0;
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
import java.lang.*;
import java.util.*;
 
// Class containing the left and right
// child of current node and the
// key value
class Node
{
    int val;
    Node left, right;
  
    // Constructor of the class
    public Node(int item)
    {
        val = item;
        left = right = null;
    }
}
 
class GFG{
     
Node root;
 
// Stores the element for each
// vertical distance
static Map mp = new HashMap<>();
  
// Function to find GCD of two numbers
static int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    // Recursively find the GCD
    return GCD(b, a % b);
}
 
// Function to traverse the tree
static void Trav(Node root, int hd)
{
    if (root == null)
        return;
 
    // Store the values in the map
    if (!mp.containsKey(hd))
        mp.put(hd, root.val);
    else
        mp.put(hd, GCD(mp.get(hd), root.val));
 
    // Recursive Calls
    Trav(root.left, hd - 1);
    Trav(root.right, hd + 1);
}
 
// Function to construct array from
// vertically positioned nodes
static void constructArray(Node root)
{
    Trav(root, 0);
     
    // Get range of horizontal distances
    int lower = Integer.MAX_VALUE, upper = 0;
    for(Map.Entry it:mp.entrySet())
    {
        lower = Math.min(lower, it.getKey());
        upper = Math.max(upper, it.getKey());
    }
     
    ArrayList ans = new ArrayList<>();
     
    // Extract the array of values
    for(int i = lower; i < upper + 1; i++)
        ans.add(mp.getOrDefault(i,0));
     
    // Print the constructed array
    System.out.print("[");
    for(int i = 0; i < ans.size() - 1; i++)
        System.out.print(ans.get(i) + ", ");
         
    System.out.print(ans.get(ans.size() - 1) + "]");
}
 
// Driver code
public static void main(String[] args)
{
    GFG tree = new GFG();
     
    Node root = new Node(5);
    root.left = new Node(4);
    root.right = new Node(7);
    root.left.left = new Node(8);
    root.left.left.right = new Node(8);
    root.left.right = new Node(10);
    root.right.right = new Node(6);
     
    // Function Call
    constructArray(root);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Class for node of binary tree
class TreeNode:
    def __init__(self, val ='', left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to find GCD of two numbers
def GCD(a, b):
    if not b:
        return a
 
    # Recursively find the GCD
    return GCD(b, a % b)
 
# Function to construct array from
# vertically positioned nodes
def constructArray(root):
   
    # Stores the element for each
    # vertical distance
    mp = {}
 
    # Function to traverse the tree
    def Trav(root, hd):
        if not root:
            return
 
        # Store the values in the map
        if hd not in mp:
            mp[hd] = root.val
        else:
            mp[hd] = GCD(mp[hd], root.val)
 
        # Recursive Calls
        Trav(root.left, hd-1)
        Trav(root.right, hd + 1)
 
    Trav(root, 0)
 
    # Get range of horizontal distances
    lower = min(mp.keys())
    upper = max(mp.keys())
 
    ans = []
 
    # Extract the array of values
    for i in range(lower, upper + 1):
        ans.append(mp[i])
 
    # Print the constructed array
    print(ans)
 
 
# Driver Code
 
# Given Tree
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(7)
root.left.left = TreeNode(8)
root.left.left.right = TreeNode(8)
root.left.right = TreeNode(10)
root.right.right = TreeNode(6)
 
# Function Call
constructArray(root)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
// Class containing the left and right
// child of current node and the
// key value
public class Node
{
    public int val;
    public Node left, right;
   
    // Constructor of the class
    public Node(int item)
    {
        val = item;
        left = right = null;
    }
}
 
class GFG{
     
// Stores the element for each
// vertical distance
static Dictionary mp = new Dictionary();
   
// Function to find GCD of two numbers
static int GCD(int a, int b)
{
    if (b == 0)
        return a;
          
    // Recursively find the GCD
    return GCD(b, a % b);
}
  
// Function to traverse the tree
static void Trav(Node root, int hd)
{
    if (root == null)
        return;
  
    // Store the values in the map
    if (!mp.ContainsKey(hd))
        mp.Add(hd, root.val);
    else
        mp[hd] = GCD(mp[hd], root.val);
  
    // Recursive Calls
    Trav(root.left, hd - 1);
    Trav(root.right, hd + 1);
}
  
// Function to construct array from
// vertically positioned nodes
static void constructArray(Node root)
{
    Trav(root, 0);
      
    // Get range of horizontal distances
    int lower = Int32.MaxValue, upper = 0;
    foreach(KeyValuePair it in mp)
    {
        lower = Math.Min(lower, it.Key);
        upper = Math.Max(upper, it.Key);
    }
      
    List ans = new List();
      
    // Extract the array of values
    for(int i = lower; i < upper + 1; i++)
        if(mp.ContainsKey(i))
            ans.Add(mp[i]);
        else
            ans.Add(0);
         
    // Print the constructed array
    Console.Write("[");
    for(int i = 0; i < ans.Count - 1; i++)
        Console.Write(ans[i] + ", ");
          
    Console.Write(ans[ans.Count - 1] + "]");
}
  
// Driver code
static public void Main()
{
     
    Node root = new Node(5);
    root.left = new Node(4);
    root.right = new Node(7);
    root.left.left = new Node(8);
    root.left.left.right = new Node(8);
    root.left.right = new Node(10);
    root.right.right = new Node(6);
      
    // Function Call
    constructArray(root);
}
}
 
// This code is contributed by rishavmahato348


Javascript


输出:
[8, 4, 5, 7, 6]

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

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