Python---树、二叉树 练习题

Python——树、二叉树相关练习题

1.一棵树是否为另一颗树的子树

问题描述:

有两个大小不同的二叉树,T1和T2,设计一种算法来判定T2是否为T1的子树。

问题示例:

例子中的T2是T1的子树,返回True,如果不是就返回Flase,图中的T2就是T1的子树。

Python---树、二叉树 练习题_第1张图片

代码:

#定义树的结构,左右置空
class TreeNode:
	def __init__(self,val):
		self.val = val
		self.left,self.right = None,None
#T1,T2为二叉树的根节点,返回值为布尔值,如果T2是T1的字数就返回True,反之为False		
class Solution:
	def get(self,root,rt):
		if root is None:
			rt.append('#')
			return
		rt.append(str(root.val))
		self.get(root.left,rt)
		self.get(root.right,rt)
	def isSubtree(self,T1,T2):
		rt = []
		self.get(T1,rt)
		t1 = ','.join(rt)
		rt = []
		self.get(T2,rt)
		t2 = ','.join(rt)
		return t1.find(t2)!= -1
#主函数中写入测试数据
if __name__ == '__main__':
	root1 = TreeNode(1)
	root1.left = TreeNode(2)
	root1.right = TreeNode(3)
	root1.right.left =TreeNode(4)
	root2 = TreeNode(3)
	root2.left = TreeNode(4)
	solution = Solution()
	print(solution.isSubtree(root1,root2))

输出结果

True

2.最小字数

1.问题描述

给出一个二叉树,找到和最小的字数,并返回其根节点。

2.问题描述

如图所示,输出为1。
Python---树、二叉树 练习题_第2张图片

代码:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

import sys
class Solution:
    def findSubtree(self, root):
        self.minumum_weight = sys.maxsize
        self.result = None
        self.helper(root)
        return self.result

    def helper(self, root):
        if root is None:
            return 0
        left_weight = self.helper(root.left)
        right_weight = self.helper(root.right)
        if left_weight + right_weight + root.val < self.minumum_weight:
            self.minumum_weight = left_weight + right_weight + root.val
            self.result = root
        return left_weight + right_weight + root.val

def printTree(root):
    res = []
    if root is None:
        print(res)
    queue = []
    queue.append(root)
    while len(queue) != 0:
        tmp = []
        length = len(queue)
        for i in range(length):
            r = queue.pop(0)
            if r.left is not None:
                queue.append(r.left)
            if r.right is not None:
                queue.append(r.right)
            tmp.append(r.val)
        res.append(tmp)
    return (res)

# 主函数
if __name__ == '__main__':
    root = TreeNode(1)
    root.left = TreeNode(-5)
    root.right = TreeNode(2)
    root.left.left = TreeNode(0)
    root.left.right = TreeNode(2)
    root.right.left = TreeNode(-4)
    root.right.right = TreeNode(-5)
    solution = Solution()
    print("最小子树的根节点是:", solution.findSubtree(root).val)

你可能感兴趣的:(数据结构,二叉树,树结构,数据结构)