Describe a topic tree substructures
Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)
Thinking
Backtracking
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
if not (pRoot2 and pRoot1) :
return False
if pRoot2.val == pRoot1.val:
left = True
right = True
if pRoot2.left:
if not self.HasSubtree(pRoot1.left, pRoot2.left):
left = False
if pRoot2.right:
if not self.HasSubtree(pRoot1.right, pRoot2.right):
right = False
if not (left and right):
if not (self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)):
return False
else:
if self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2):
return True
else:
return False
return True
Topic two
Operation of a given binary tree, the binary tree is converted into a source image.
Enter a description:
Mirroring definition of binary tree: binary source 8 / \ 610 / \ / \ 57911 mirror binary 8 / \ 106 / \ / \ 11975
Thinking
Recursion
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
if root:
temp = root.right
root.right = root.left
root.left = temp
self.Mirror(root.left)
self.Mirror(root.right)
return root