【问题标题】:Given a BST, print all the possible combinations of differents nodes pairs给定一个 BST,打印不同节点对的所有可能组合
【发布时间】:2021-01-03 12:16:05
【问题描述】:

假设您有以下 BST:

  4
 /  \
2    8 

使用以下 C 结构实现:

typedef struct node{
    int data;
    struct node* left;
    struct node* right;
}node; 

输出将是:

(4,2)
(4,8)
(2,4)
(2,8)
(8,4)
(8,2) 

这个算法如何实现?

是否有可能以比 O(n^2 - n) 更好的方式在运行时提供正确输出的算法实现? p>

【问题讨论】:

  • 我不这么认为。因为无论如何输出对的数量都是 n^2 - n。
  • 你走树。在每个节点上,您执行第二次独立遍历。在每个嵌套遍历的每个节点,输出第一次遍历的当前节点和嵌套遍历的当前节点形成的pair,除非它们是同一个节点。您可以使用深度优先或广度优先遍历;无论哪种方式,您都会得到所有配对,但(通常)顺序不同。

标签: c algorithm binary-search-tree combinations permutation


【解决方案1】:

我已经找到了解决办法:

是否有可能以比 O(n^2 - n) 更好的方式在运行时提供正确输出的方式实现该算法?

不,不可能有比 O(n^2 - n) 更好的运行时。

这个算法如何实现?

void printPairsHelper(node* root, node* temp){
    if (!root) return;
 
    if (root != temp) printf("%d, %d\n", root->data, temp->data);
 
    printPairsHelper(root->left, temp);
    printPairsHelper(root->right, temp);
}

void printPairs(node* root, node* curr){
    if (!curr) return;
 
    printPairsHelper(root, curr);
 
    printPairs(root, curr->left);
    printPairs(root, curr->right);
}

用法:

//Declare the BST
node* root = NULL;

//Add some nodes to the BST

//...

//Call the function
printPairs(root, root);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2016-09-02
    • 1970-01-01
    • 2013-04-29
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多