zoukankan      html  css  js  c++  java
  • Given an inorder traversal only for a binary tree (not necessarily a BST), …

    Given an in-order traversal only for a binary tree (not necessarily a BST), give a pseudo code to generate all possible binary trees for this traversal sequence.

    A: 数学归纳法

    Firstly of all, with ‘n’ number of nodes, there are (2n)!/n!*(n+1)!

    If like the normal definition, in-order is left child->self->right child.
    Then in the sequence with length n, we call Partition(sequence) which iteratively pick each one to be the root. All the values on left make the left sub tree and others on right make the right sub tree. So you can call the Partition(subsequence) recursively.

    But if you want to know the number of possible trees, I think inductive method could help. If there are N(k) trees correspond to a sequence with length k, then what is N(k+1) by adding the new value or node to the tail of the sequence? I think the answer is 2*N(k). Because you can treat the new node as the last right child or the parent with the previous tree(all possible trees corresponding to sequence k) as its left-child. By knowing N(1) is 1, you have 2^(n-1) for sequence n.

  • 相关阅读:
    edu_2_4_1
    edu_2_3_2
    edu_2_3_1
    edu_2_2_2
    edu_2_1_1
    edu_2_2_1
    hdu 1270 小希的数表
    hdu 2151 worm
    hdu1089 Ignatius's puzzle
    hdu 2190 悼念512汶川大地震遇难同胞——重建希望小学
  • 原文地址:https://www.cnblogs.com/yayagamer/p/2304364.html
Copyright © 2011-2022 走看看