Home > Backend Development > C++ > body text

Query the minimum weight in the subtree starting from node X and distance at most D

王林
Release: 2023-08-25 11:25:07
forward
1463 people have browsed it

Query the minimum weight in the subtree starting from node X and distance at most D

When doing computer programming, sometimes it is necessary to find the minimum weight of a subtree originating from a specific node, provided that the subtree cannot contain nodes that are more than D units away from the specified node. This problem arises in various fields and applications, including graph theory, tree-based algorithms, and network optimization.

A subtree is a subset of a larger tree structure, with the specified node serving as the root node of the subtree. A subtree contains all descendants of the root node and their connecting edges. A node's weight refers to a specific value assigned to that node, which can represent its importance, significance, or other relevant metrics. In this problem, the goal is to find the minimum weight among all nodes in a subtree while limiting the subtree to nodes that are at most D units away from the root node.

In the following article, we will delve into the complexity of mining minimum weights from subtrees whose boundaries are no more than D distance nodes from node X.

method

  • Method 1 - Depth First Search (DFS) One of the most common and straightforward ways to solve this problem is to use a depth first search (DFS) traversal of the subtree.

  • Method 2 − Another way to solve this problem is to use breadth-first search (BFS) to traverse the subtree.

grammar

The following syntax declares a function named findMinimumWeight, which accepts two parameters. The first parameter Node* x is a pointer to a node in the binary tree, and the second parameter int d is an integer representing the distance. This function returns an integer minWeight. The implementation of the algorithm to find the minimum weight in the subtree starting from node x is not specified in the given code snippet.

int findMinimumWeight(Node* x, int d) {
   // Implementation of the algorithm
   // ...
   return minWeight;
}
Copy after login

where -

  • Node* x represents a pointer to the root node of the tree.

  • int d represents the constraint on the maximum distance between the node in the subtree and the root node.

algorithm

A complex challenge in computer science is to determine the minimum weight of a subtree starting from a given node X and spanning no more than D nodes. There are several algorithms to solve this problem. Here we provide a high-level overview of the approach −

Step 1 - Start with node X as the root of the subtree.

Step 2 - Traverse the subtree in a depth-first manner, carefully recording the distance of each node from the root node.

Step 3 - Maintain a variable to track the smallest weight encountered so far.

Step 4 - At each node, evaluate whether the distance from the root node to that node is within the D limit. If so, update the minimum weight variable using the weight of the current node.

Step 5 - Repeat steps 3 and 4 for all nodes in the subtree.

Step 6 - Finally, return the minimum weight obtained from the subtree.

method 1

One of the simplest and most common solutions to this challenge is to exploit depth-first search (DFS) exploration of subtrees. In this approach, we traverse the subtree of a given node in a depth-first manner, visiting each node and its descendants before proceeding to the next sibling. At each node, we evaluate its distance from the root node, and if it falls within the specified limits, we modify the smallest weight found so far. The running time complexity of this approach is O(n), where n represents the number of nodes in the subtree, since each node is visited only once.

Example

The code provided constitutes a program designed to determine the minimum weight of a node in a subtree that is at most "d" distance away from a node "X" in a binary tree. A binary tree is represented by a structure called a "node", which contains a weight, a reference to its left child node, and a reference to its right child node.

The main function "findMinimumWeightDFS" takes node "x" and an integer "d" as input and returns the minimum weight of the node that is at most "d" distance away from "x". This function uses the helper function "findMinimumWeightDFS", which performs a depth-first search (DFS) on the binary tree and updates the minimum weight found so far.

The minimum weight is initialized to a larger value and modified during DFS exploration if the current node is at most 'd' distance from the root node. This function returns the final minimum weight found after DFS exploration.

#include <iostream>
#include <climits>
using namespace std;

// Definition of Node structure
struct Node {
   int weight;
   Node* left;
   Node* right;
   Node(int w) : weight(w), left(nullptr), right(nullptr) {}
};

// Function to perform DFS traversal and find minimum weight
void findMinimumWeightDFS(Node* x, int d, int distance, int& minWeight) {
   // Base case: if the current node is null or distance exceeds D, return
   if (x == nullptr || distance > d) {
      return;
   }

   // If the current node is at most D-distant from the root node, update minWeight
   if (distance <= d) {
      minWeight = min(minWeight, x->weight);
   }

   // Recursively perform DFS on the left and right children of the current node
   findMinimumWeightDFS(x->left, d, distance + 1, minWeight);
   findMinimumWeightDFS(x->right, d, distance + 1, minWeight);
}

// Function to find minimum weight from subtree of at most D-distant nodes from node X using DFS
int findMinimumWeightDFS(Node* x, int d) {
   int minWeight = INT_MAX; // Initialize minWeight to a large value
   findMinimumWeightDFS(x, d, 0, minWeight); // Perform DFS traversal
   return minWeight; // Return the minimum weight obtained
}

// Driver code
int main() {
    // Create a sample binary tree
   Node* root = new Node(1);
   root->left = new Node(2);
   root->right = new Node(3);
   root->left->left = new Node(4);
   root->left->right = new Node(5);
   root->right->left = new Node(6);
   root->right->right = new Node(7);

   // Test the findMinimumWeightDFS function
   int d = 2;
   int minWeight = findMinimumWeightDFS(root, d);
   cout << "Minimum weight from subtree of at most " << d << "-distant nodes from node X: " << minWeight << endl;

   return 0;
}
Copy after login

Output

Minimum weight from subtree of at most 2-distant nodes from node X: 1
Copy after login
Copy after login

Method 2

Another strategy to address this challenge is to employ breadth-first search (BFS) to explore subtrees. In this approach, we traverse the subtree of a given node in a breadth-first manner, visiting all the node's children before proceeding to the next level. At each node, we evaluate its distance from the root node, and if it is within the specified limits, we modify the minimum weight found so far. The time complexity of this method is O(n), where n represents the number of nodes in the subtree, since each node is visited only once. However, the space complexity of this method is larger than the depth-first search (DFS) method because it requires a queue to keep track of nodes to be explored.

示例

该代码构成了一个程序,旨在确定二叉树中节点的最小权重,给定距根节点的最大距离“d”。该策略涉及对二叉树进行广度优先搜索 (BFS) 探索,并将每个节点及其与根节点的距离存储在队列中。该函数以根节点及其距离为 0 启动,并将其添加到队列中。

然后,它迭代地从队列的前面检索节点,如果节点的距离至多为“d”,则更新最小权重。如果该节点拥有左或右后代,它会将孩子添加到具有更新距离的队列中。该函数将继续执行,直到队列为空。最后,函数返回BFS探索得到的最小权重。

#include <iostream>
#include <queue>
#include <climits>
using namespace std;

// Definition of Node structure
struct Node {
   int weight;
   Node* left;
   Node* right;
   Node(int w) : weight(w), left(nullptr), right(nullptr) {}
};

// Function to perform BFS traversal and find minimum weight
int findMinimumWeightBFS(Node* x, int d) {
   queue<pair<Node*, int>>q; // Create a queue to store nodes and their distances
   q.push({x, 0}); // Push the root node and its distance (0) to the queue
   int minWeight = INT_MAX; // Initialize minWeight to a large value

   while (!q.empty()) {
      Node* curr = q.front().first; // Get the current node from the front of the queue
      int distance = q.front().second; // Get the distance of the current node from the root
      q.pop(); // Pop the current node from the queue

      // If the current node is at most D-distant from the root node, update minWeight
      if (distance <= d) {
         minWeight = min(minWeight, curr->weight);
      }

      // If the current node has left child, push it to the queue with updated distance
      if (curr->left) {
         q.push({curr->left, distance + 1});
      }

      // If the current node has right child, push it to the queue with updated distance
      if (curr->right) {
         q.push({curr->right, distance + 1});
      }
   }

   return minWeight; // Return the minimum weight obtained
}

// Driver code
int main() {
   // Create a sample binary tree
   Node* root = new Node(1);
   root->left = new Node(2);
   root->right = new Node(3);
   root->left->left = new Node(4);
   root->left->right = new Node(5);
   root->right->left = new Node(6);
   root->right->right = new Node(7);

   // Test the findMinimumWeightBFS function
   int d = 2;
   int minWeight = findMinimumWeightBFS(root, d);
   cout << "Minimum weight from subtree of at most " << d << "-distant nodes from node X: " << minWeight << endl;

   return 0;
}
Copy after login

输出

Minimum weight from subtree of at most 2-distant nodes from node X: 1
Copy after login
Copy after login

结论

本文介绍了如何使用 C++ 从二叉树中与特定节点 X 相距最多 D 距离的节点子树中获取最小权重。我们研究了深度优先搜索 (DFS) 和广度优先搜索 (BFS) 方法,并提供了每种方法的实现代码和示例结果。

The above is the detailed content of Query the minimum weight in the subtree starting from node X and distance at most D. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template