【问题标题】:Rooted tree with huge depth - DFS Traversal algorithm performance具有巨大深度的有根树 - DFS 遍历算法性能
【发布时间】:2017-05-02 00:20:12
【问题描述】:

今天,我学习了 3 个针对有根树的 DFS(深度优先搜索)遍历,即 有序、前序和后序遍历。

例如,如果我考虑预购遍历,

typedef struct SiblingTreeNode {
    struct SiblingTreeNode *parent;
    void *item;
    struct SiblingTreeNode *firstChild;
    struct SiblingTreeNode *nextSibling;
} Node;

typedef struct LCRSTree {
    Node *root;
    int size;
} Tree;


void preOrderTraverse(Node * node) {
    visit(node);

    if (node->firstChild) {
        printf("\n|");
        preOrderTraverse(node->firstChild);
    }

    if (node->nextSibling) {
        printf("-->");
        preOrderTraverse(node->nextSibling);
    }
}

void preOrder(Tree *tree) {
    preOrderTraverse(tree->root);
}

然后按以下顺序访问节点,

实际用于 NMS(网络管理系统)应用程序,我们使用有根树(LCRS 表示)来维护网络元素(指标)的层次结构,叶节点的深度非常大。

渐近地,前序遍历的空间复杂度为O(d),其中d是最低叶子的深度。

在应用这 3 个遍历中的任何一个时,由于堆栈溢出,应用程序很有可能崩溃。

例如 - 如果您考虑访问节点序列(以上)调用堆栈从根到叶维护,当您访问第三个节点时。

使用上面给定的Tree 表示,在不维护显式数据结构(如堆栈)的情况下,如何在有根树上优化遍历算法?

注意:在构造中,Tree 看起来像 this

【问题讨论】:

    标签: c algorithm data-structures tree traversal


    【解决方案1】:

    Pre-order traversal 有一个非递归的解决方案,它在递归中使用堆栈数据结构而不是调用堆栈。 如果内存仍然是个问题,您可以设计一个堆栈来将其中的一部分卸载到存储中,并在需要时重新加载。

    void iterativePreorder() {
        TreeNode top;
        if (root == null)
            return;
    
        Stack<SiblingTreeNode> st = new Stack<SiblingTreeNode>();
        st.push(root);
    
        while (!st.empty()) {
            top = st.pop();
            //do traversal effect
            if (top.right != null)
                st.push(top.right);
            if (top.left != null)
                st.push(top.left);
        }
    }
    

    【讨论】:

    • 堆上没有显式栈,我们有遍历算法吗?
    • 大多数树遍历都是基于 DFS 和 BFS 算法。 DFS 是基于堆栈的,而 BFS 是基于队列的。”我认为很难避免它们,因为需要保持遍历状态。您可以将一些堆栈卸载到存储(HDD、SSD)。
    • 中序、前序和后序是有根树的 DFS 遍历。如何在有根树上执行 BFS?
    • 从根开始,将两个孩子加入队列。当队列不为空时,将一个节点出队,将它的孩子添加到队列中等等。它传递树中的所有节点,但逐级传递。
    • hmm 让我现在迭代地尝试 DFS 和 BFS
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多