【问题标题】:Generate the post-order traversal given the in-order and pre-order traversal给定中序和前序遍历生成后序遍历
【发布时间】:2012-03-11 21:42:19
【问题描述】:

我看到代码贴在这里: How do I output the preorder traversal of a tree given the inorder and postorder tranversal?

但我很难理解逻辑,尤其是树右侧部分的递归:

postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);

任何帮助将不胜感激。

【问题讨论】:

    标签: c data-structures binary-tree


    【解决方案1】:

    假设binary expression tree 以及中序、前序和后序遍历如何作用于它:

    1. inorder:左子树,当前根,右子树
    2. preorder:当前根、左子树、右子树
    3. postorder: 左子树,右子树,当前根

    现在是当前代码,首先标识左右子树。我们知道预序数组的第一个元素是我们的根,我们可以在中序数组中找到对应的根。我们知道根之前的所有元素都是左子树的元素,它之后的所有元素都是右子树的元素。

    我们想产生后序遍历,所以我们递归地继续左子树:

       postorder(preorder, prestart+1, inorder, inostart, i-inostart);
    
    1. prestart+1: 因为左子树的根在前序遍历中就在当前根的后面
    2. i-inostart: 因为 i 是我们的根在中序数组中的索引,所以 i-inostart 将是左子树的大小

    然后是右子树:

       postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);
    
    1. prestart+i-inostart+1: 正如我上面所说的 i-inostart 是左子树的大小,而且我们知道在预排序数组中右的根子树将出现在当前根和整个子树之后,因此它的索引将是 prestart+i-inostart+1
    2. i+1: 因为在中序数组中,根的索引是i,之后的元素应该是中序数组中右子树的开始
    3. length-i+inostart-1: 因为右子树的大小将是 length 减去左子树的大小再减去 1(根)

    然后输出我们当前的根:

       cout<<preorder[prestart]<<" ";
    

    递归地这样做会导致树的后序遍历。

    【讨论】:

      猜你喜欢
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      相关资源
      最近更新 更多