1. 程式人生 > 實用技巧 >前序遍歷+中序遍歷=後序遍歷

前序遍歷+中序遍歷=後序遍歷

def find_post(pre_str: str, mid_str: str) -> str:
    if not pre_str:
        return ""
    post_str = ""
    root_in_mid = mid_str.find(pre_str[0])
    ltree_rlimit = 0
    for item in mid_str[:root_in_mid]:
        locate = pre_str.find(item)
        if ltree_rlimit < locate:
            ltree_rlimit = locate
    root_in_mid = mid_str.find(pre_str[0])
    # ltree
    post_str += find_post(pre_str[1:ltree_rlimit + 1], mid_str[:root_in_mid])
    # rtree
    post_str += find_post(pre_str[ltree_rlimit + 1:], mid_str[root_in_mid + 1:])
    post_str += pre_str[0]
    return post_str


def func():
    # please define the python3 input here.
    # For example: a,b = map(int, input().strip().split())
    pre_visit = input().strip()
    mid_visit = input().strip()
    # please finish the function body here.
    post_visit = find_post(pre_visit, mid_visit)
    # please define the python3 output here. For example: print().
    print(post_visit)


if __name__ == "__main__":
    func()