繁体   English   中英

如何从最小到最大打印2-3棵树?

[英]How to print 2-3 tree from min to max?

我不知道该如何处理算法。 我在想这样的事情:

TreeNode n = root;
while(n.first.first!=0){ 
    n=n.first;
} // finding the leftMost parent
//printing the first child key, then first num of parent, then second child.. and so on

有人有更好的主意吗?

根据2-3树的定义,您可以遇到3种类型的节点:

  • 具有2个子对象和1个值的内部节点
  • 具有3个子节点和2个值的内部节点
  • 没有子项且值为1或2的叶子

有了这些信息,您可以使用递归方法从根节点开始遍历节点。 如果符合叶节点,则只需打印值。 在其他情况下,该方法必须针对最左侧的节点(跳转到左侧的节点)调用自身,然后输出第一个值,然后跳转至下一个节点,依此类推。 之后,该方法结束,因此整个算法将结束(如果实际节点是根节点)或跳回到父节点(如果实际节点是内部子节点)

这是伪代码。 我将实际的实现留给自己。 研究一下并确保您了解方法的流程(可以使用调试器并跟踪实际参数)

/* you start algorithm by calling recursivePrint(root) */

void recursivePrint(node){

    if (node is a leaf){

        /* Here print node's value/values */

    } else if (node has 2 children){

        recursivePrint(node.leftChild);
        /* Here print node's value */
        recursivePrint(node.rightChild);

    } else if (node has 3 children)

        recursivePrint(node.leftChild);
        /* Here print node's left value */
        recursivePrint(node.middleChild);
        /* Here print node's right value */
        recursivePrint(node.rightChild)

    }

    /* Shouldn't be other cases in 2-3 trees */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM