c# - 在列表中水平返回二叉树

标签 c# algorithm binary-search-tree

如何在列表中水平返回二叉搜索树?是否可以递归?

enter image description here

预期列表:8、3、10、1、6、14、4、7、13

[编辑] 由于索引,我设法在一个数组中完成它,因为我们知道节点 i 的左儿子将是 2i+1,而右节点将是 2i+2。不过,我不知道如何使用列表来做到这一点。

最佳答案

您需要使用呼吸优先搜索。在伪代码中:

BreadthFirstSearch(Node root):

    create empty list L
    create empty queue Q

    Q.enqueue(root)

    while Q is not empty:
        current = Q.dequeue()

        L.append(current)
        if current.left is not null:
            Q.enqueue(current.left)
        if current.right is not null:
            Q.enqueue(current.right)

    return L

或者,递归地做

BreadthFirstSearch(Queue Q, List L):
    if Q is empty:
        return

    current = Q.dequeue()
    L.append(current)

    if current.left is not null:
        Q.enqueue(current.left)
    if current.right is not null:
        Q.enqueue(current.right)

    BreadthFirstSearch(Q, L)

对于第二种方法,您可以这样调用它:

ConvertBSTToList(Node root):
    create empty queue Q
    create empty list L

    Q.enqueue(root)
    BreadthFirstSearch(Q,L)

    return L

关于c# - 在列表中水平返回二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34949952/

相关文章:

c# - 使用 C# 发布自动化 mysqldump

c# - 如何从字符串中剪切指定的单词

algorithm - 算法的渐近分析 :how to insert k new elements into a sorted list of size n in time O(k log k + n)

c - 我怎样才能构建这棵树?

尝试打印二叉树根部的值时崩溃

C++链接二叉搜索树(DeleteTree)

c# - 具有通用测试的 Nunit 基类

C# EF6 回滚更改,EntityState.Unchanged 错误

c# - 打开 App 时不显示 PUSH

algorithm - 给定两个数组 a 和 b。找到所有元素对 (a1,b1),使得 a1 属于数组 A,b1 属于数组 B,其和 a1+b1 = k