# 输入两棵二叉树A，B，判断B是不是A的子结构。（ps：我们约定空树不是任意一个树的子结构）


python
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
result = False
if pRoot1 != None and pRoot2 != None:
if pRoot1.val == pRoot2.val:
result = self.DoesTree1haveTree2(pRoot1, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.left, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.right, pRoot2)
return result
# 用于递归判断树的每个节点是否相同
# 需要注意的地方是: 前两个if语句不可以颠倒顺序
# 如果颠倒顺序, 会先判断pRoot1是否为None, 其实这个时候pRoot2的结点已经遍历完成确定相等了, 但是返回了False, 判断错误
def DoesTree1haveTree2(self, pRoot1, pRoot2):
if pRoot2 == None:
return True
if pRoot1 == None:
return False
if pRoot1.val != pRoot2.val:
return False
return self.DoesTree1haveTree2(pRoot1.left, pRoot2.left) and self.DoesTree1haveTree2(pRoot1.right, pRoot2.right)


# -*- coding:utf-8 -*-
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
def same(pRoot1, pRoot2):
if not pRoot2:
return True
elif pRoot1 and pRoot2:
if pRoot1.val == pRoot2.val:
return same(pRoot1.left, pRoot2.left) and same(pRoot1.right, pRoot2.right)
else:
return False
else:
return False
if pRoot1 and pRoot2:
return same(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)
else:
return False


# 操作给定的二叉树，将其变换为源二叉树的镜像。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if root is None:
return
tmp = root.right
root.right = root.left
root.left = tmp
self.Mirror(root.left)
self.Mirror(root.right)
return root
`
09-10 3653
08-29 1407

06-02 2835
08-16 4万+
11-02 5万+
02-27
12-19
08-05 1万+