根据二叉树的前序和后续遍历求二叉树的叶子节点数

题目描述:根据二叉树的前序和中续遍历求二叉树的叶子节点数
输入:
前序[‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’]
后续[‘C’,‘B’,‘D’,‘A’,‘E’,‘G’,‘F’]
输出:4
首先根据前序和后续遍历恢复二叉树,然后再统计叶子结点数量。

Python实现:

#!/usr/bin/python
# -*- coding: UTF-8 -*-


class TreeNode():
    def __init__(self,val,left=None,right=None):
        self.val=val
        self.left=left
        self.right=right
def pre_print(root):#前序遍历二叉树输出
    if root==None:
        return
    else:
        print(root.val,end=" ")
        pre_print(root.left)
        pre_print(root.right)

def in_print(root):#中序遍历二叉树输出
    if root==None:
        return
    else:
        pre_print(root.left)
        print(root.val, end=" ")
        pre_print(root.right)

def after_print(root):#后序遍历二叉树输出
    if root==None:
        return
    else:
        pre_print(root.left)
        pre_print(root.right)
        print(root.val, end=" ")

def restruct_tree(pre_order, in_order):
    '''
    恢复二叉树
    :param pre_order:
    :param in_order:
    :return:
    '''
    # 排出两种特殊情况
    if len(pre_order) == 0:
        return None
    elif len(in_order) == 1:
        return TreeNode(in_order[0])
    else:
        root = pre_order[0]
        depth = in_order.index(root)
        temp = TreeNode(root)
        temp.left = restruct_tree(pre_order[1: depth + 1], in_order[:depth])
        temp.right = restruct_tree(pre_order[depth + 1:], in_order[depth + 1:])
    return temp


def count_yezi(root):
    '''
    计算叶子结点数量
    :param root:
    :return:
    '''
    if root == None:
       return 1
    else:
       return count_yezi(root.left) + count_yezi(root.right)


# n = int(input())
# pre = []
# mid = []
# x = input().split(' ')
# y = input().split(' ')
# for i in range(n):
#     pre.append(int(x[i]))
#     mid.append(int(y[i]))

pre_order=['A','B','C','D','E','F','G']#前序
in_order=['C','B','D','A','E','G','F']#中序
temp = restruct_tree(pre_order, in_order)

#pre_print(temp)


num = count_yezi(temp)
print(int(num / 2))

参考:https://www.cnblogs.com/chenminyu/p/11699270.html

猜你喜欢

转载自blog.csdn.net/broccoli2/article/details/108035745