📌  相关文章
📜  通过填充给定的空树来最小化节点值的总和,使得每个节点都是其子节点的 GCD

📅  最后修改于: 2022-05-13 01:56:06.748000             🧑  作者: Mango

通过填充给定的空树来最小化节点值的总和,使得每个节点都是其子节点的 GCD

给定一棵由N个没有值的节点和一个整数X组成的二叉树,它表示根节点的值,任务是找到给定树的所有节点值的最小总和,使得每个节点的值node 必须是其子节点的 GCD 值。此外,没有两个兄弟姐妹可以具有相同的值。

例子:

方法:为了最小化总和,两个孩子都可以有X2*X的值,其中X是父母的值。现在,如果节点只有一个子节点,那么它的值将等于它的父节点。但是为了决定哪个孩子应该有X2*X的值以获得最小和,将考虑每个节点的每个子树的深度。具有更大深度的孩子将被赋予X值,以便它可以将其转移给更多的孩子,而另一个孩子将获得2*X的值。请按照以下步骤解决此问题:

  1. 找到每个节点的深度并将其存储在地图中,并与节点地址一起作为键。
  2. 现在,从根节点开始执行 DFS 遍历,如果节点的深度大于其兄弟节点,则在每次调用中为节点分配X值。否则,分配值2*X
  3. 完成上述步骤后,在回溯的同时找到左右孩子值的总和,并返回总和,即每次调用中左孩子、右孩子和当前节点的值之和。
  4. 完成上述步骤后,打印从DFS 调用返回的值作为可能的最小总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Structure of Tree Node
class Node {
public:
    int val;
    Node *left, *right;
    Node(int val)
    {
        this->val = val;
        left = NULL;
        right = NULL;
    }
};
 
class Tree {
public:
    unordered_map depth;
 
    // Function to find the depth of all
    // nodes and store it in map depth
    int findDepth(Node* cur)
    {
        int mx = 0;
        if (cur->left) {
            mx = findDepth(cur->left);
        }
        if (cur->right) {
            mx = max(mx, findDepth(cur->right));
        }
 
        // Update and return the maximum
        // depth of the tree
        return depth[cur] = mx + 1;
    }
 
    // Function to assign values to nodes
    // and return the minimum sum possible
    int dfs(Node* cur, bool flag, int parValue)
    {
        if (parValue != -1) {
            if (flag)
                cur->val = parValue;
            else
                cur->val = parValue * 2;
        }
        int l = 0, r = 0;
        if (cur->left && cur->right) {
            if (depth[cur->left] > depth[cur->right]) {
                l = dfs(cur->left, 1, cur->val);
                r = dfs(cur->right, 0, cur->val);
            }
            else {
                l = dfs(cur->left, 0, cur->val);
                r = dfs(cur->right, 1, cur->val);
            }
        }
        else if (cur->left) {
            l = dfs(cur->left, 1, cur->val);
        }
        else if (cur->right) {
            r = dfs(cur->right, 1, cur->val);
        }
 
        return l + r + cur->val;
    }
 
    // Function to find the minimum sum
    // for the given tree by assign the
    // values to the node according to
    // the given criteria
    int minimumSum(Node* root)
    {
        // Find the maximum depth
        findDepth(root);
 
        // Calculate the minimum sum and
        // return it
        return dfs(root, 1, -1);
    }
};
 
// Driver Code
int main()
{
 
    // Given root node value
    int X = 2;
 
    // Given empty tree structure
    Node* root = new Node(X);
    root->left = new Node(-1);
    root->right = new Node(-1);
    root->left->left = new Node(-1);
    root->left->right = new Node(-1);
    root->left->right->left = new Node(-1);
    root->left->right->right = new Node(-1);
    root->left->right->right->left = new Node(-1);
 
    Tree t;
 
    // Fill the tree and print minimum tree sum
    cout << t.minimumSum(root);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class Main
{
    // Structure of Tree Node
    static class Node {
         
        public int val;
        public Node left, right;
         
        public Node(int val)
        {
            this.val = val;
            left = right = null;
        }
    }
     
    static HashMap depth = new HashMap<>();
     
    // Function to find the depth of all
    // nodes and store it in map depth
    static int findDepth(Node cur)
    {
        int mx = 0;
        if (cur.left != null) {
            mx = findDepth(cur.left);
        }
        if (cur.right != null) {
            mx = Math.max(mx, findDepth(cur.right));
        }
     
        // Update and return the maximum
        // depth of the tree
        depth.put(cur, mx + 1);
        return depth.get(cur);
    }
     
    // Function to assign values to nodes
    // and return the minimum sum possible
    static int dfs(Node cur, int flag, int parValue)
    {
        if (parValue != -1) {
            if (flag == 1)
                cur.val = parValue;
            else
                cur.val = parValue * 2;
        }
        int l = 0, r = 0;
        if (cur.left != null && cur.right != null) {
            if (depth.containsKey(cur.left) && depth.containsKey(cur.right) && depth.get(cur.left) > depth.get(cur.right)) {
                l = dfs(cur.left, 1, cur.val);
                r = dfs(cur.right, 0, cur.val);
            }
            else {
                l = dfs(cur.left, 0, cur.val);
                r = dfs(cur.right, 1, cur.val);
            }
        }
        else if (cur.left != null) {
            l = dfs(cur.left, 1, cur.val);
        }
        else if (cur.right != null) {
            r = dfs(cur.right, 1, cur.val);
        }
     
        return (l + r + cur.val);
    }
     
    // Function to find the minimum sum
    // for the given tree by assign the
    // values to the node according to
    // the given criteria
    static int minimumSum(Node root)
    {
        // Find the maximum depth
        findDepth(root);
     
        // Calculate the minimum sum and
        // return it
        return dfs(root, 1, -1);
    }
     
  // Driver code
    public static void main(String[] args)
    {
       
        // Given root node value
        int X = 2;
         
        // Given empty tree structure
        Node root = new Node(X);
        root.left = new Node(-1);
        root.right = new Node(-1);
        root.left.left = new Node(-1);
        root.left.right = new Node(-1);
        root.left.right.left = new Node(-1);
        root.left.right.right = new Node(-1);
        root.left.right.right.left = new Node(-1);
         
        // Fill the tree and print minimum tree sum
        System.out.print(minimumSum(root));
    }
}
 
// This code is contributed by suresh07.


Python3
# Python3 program for the above approach
 
# Structure of Tree Node
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
 
depth = {}
    
# Function to find the depth of all
# nodes and store it in map depth
def findDepth(cur):
    mx = 0
    if (cur.left != None):
        mx = findDepth(cur.left)
    if (cur.right != None):
        mx = max(mx, findDepth(cur.right))
 
    # Update and return the maximum
    # depth of the tree
    depth[cur] = mx + 1
    return depth[cur]
 
# Function to assign values to nodes
# and return the minimum sum possible
def dfs(cur, flag, parValue):
    if (parValue != -1):
        if flag:
            cur.val = parValue
        else:
            cur.val = parValue * 2
    l, r = 0,  0;
    if (cur.left != None and cur.right != None):
        if ((cur.left in depth) and (cur.right in depth) and depth[cur.left] > depth[cur.right]):
            l = dfs(cur.left, 1, cur.val)
            r = dfs(cur.right, 0, cur.val)
        else:
            l = dfs(cur.left, 0, cur.val)
            r = dfs(cur.right, 1, cur.val)
    elif (cur.left != None):
        l = dfs(cur.left, 1, cur.val)
    elif (cur.right != None):
        r = dfs(cur.right, 1, cur.val)
 
    return (l + r + cur.val)
 
# Function to find the minimum sum
# for the given tree by assign the
# values to the node according to
# the given criteria
def minimumSum(root):
   
    # Find the maximum depth
    findDepth(root)
 
    # Calculate the minimum sum and
    # return it
    return dfs(root, 1, -1)
 
# Given root node value
X = 2
 
# Given empty tree structure
root = Node(X)
root.left = Node(-1)
root.right = Node(-1)
root.left.left = Node(-1)
root.left.right =Node(-1)
root.left.right.left = Node(-1)
root.left.right.right = Node(-1)
root.left.right.right.left = Node(-1);
 
# Fill the tree and print minimum tree sum
print(minimumSum(root))
 
# This code is contributed by mukesh07.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Structure of Tree Node
    class Node {
        
        public int val;
        public Node left, right;
        
        public Node(int val)
        {
            this.val = val;
            left = right = null;
        }
    }
     
    static Dictionary depth = new Dictionary();
    
    // Function to find the depth of all
    // nodes and store it in map depth
    static int findDepth(Node cur)
    {
        int mx = 0;
        if (cur.left != null) {
            mx = findDepth(cur.left);
        }
        if (cur.right != null) {
            mx = Math.Max(mx, findDepth(cur.right));
        }
    
        // Update and return the maximum
        // depth of the tree
        depth[cur] = mx + 1;
        return depth[cur];
    }
    
    // Function to assign values to nodes
    // and return the minimum sum possible
    static int dfs(Node cur, int flag, int parValue)
    {
        if (parValue != -1) {
            if (flag == 1)
                cur.val = parValue;
            else
                cur.val = parValue * 2;
        }
        int l = 0, r = 0;
        if (cur.left != null && cur.right != null) {
            if (depth.ContainsKey(cur.left) && depth.ContainsKey(cur.right) && depth[cur.left] > depth[cur.right]) {
                l = dfs(cur.left, 1, cur.val);
                r = dfs(cur.right, 0, cur.val);
            }
            else {
                l = dfs(cur.left, 0, cur.val);
                r = dfs(cur.right, 1, cur.val);
            }
        }
        else if (cur.left != null) {
            l = dfs(cur.left, 1, cur.val);
        }
        else if (cur.right != null) {
            r = dfs(cur.right, 1, cur.val);
        }
    
        return (l + r + cur.val);
    }
    
    // Function to find the minimum sum
    // for the given tree by assign the
    // values to the node according to
    // the given criteria
    static int minimumSum(Node root)
    {
        // Find the maximum depth
        findDepth(root);
    
        // Calculate the minimum sum and
        // return it
        return dfs(root, 1, -1);
    }
     
  static void Main() {
    // Given root node value
    int X = 2;
    
    // Given empty tree structure
    Node root = new Node(X);
    root.left = new Node(-1);
    root.right = new Node(-1);
    root.left.left = new Node(-1);
    root.left.right = new Node(-1);
    root.left.right.left = new Node(-1);
    root.left.right.right = new Node(-1);
    root.left.right.right.left = new Node(-1);
    
    // Fill the tree and print minimum tree sum
    Console.Write(minimumSum(root));
  }
}
 
// This code is contributed by divyesh072019.


Javascript



输出
22

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