中缀,前缀或后缀顺序通过BST得到降序打印元素

Infix, prefix or postfix order trough BST to get descending order of printed elements

本文关键字:BST 降序 元素 打印 前缀 后缀 顺序 中缀      更新时间:2023-10-16

我知道如果我们以中缀顺序打印BST,我将得到树中包含的元素的升序。如何得到降序?使用后缀还是前缀?

后缀和前缀都不会给出降序。您需要再次使用中缀,但是首先从右子节点下降(当正常遍历首先从左节点下降时)。

p = root;
push(p);
p = p->rightchild;
while(stack is not empty) {    
    while(p != NULL) {
        push(p);
        p = p->rightchild;
    }
    p = pop();
    print p->data;     
    if(p->leftchild != NULL) {
        p = p->leftchild;
    }
}