题解 | #树的子结构#
树的子结构
http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
中序遍历,匹配也使用中序遍历。
中序遍历非递归模板
# -*- 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):
stack = []
p = pRoot1
if pRoot2 == None:
return False
while (stack != None and len(stack) > 0 ) or p != None:
while p != None:
stack.append(p)
p = p.left
p = stack.pop(-1)
if p.val == pRoot2.val:
if self.Ischild(p, pRoot2):
return True
p = p.right
return False
def Ischild(self,proot1,proot2):
stack = []
stack2 = []
p = proot1
p2 = proot2
while ((stack != None and len(stack) > 0 ) and (stack2 != None and len(stack2) > 0) ) or (p != None and p2 != None):
while p != None and p2 != None:
stack.append(p)
stack2.append(p2)
p = p.left
p2 = p2.left
if p2 != None:
return False
p = stack.pop(-1)
p2 = stack2.pop(-1)
if p.val != p2.val:
return False
p = p.right
p2 = p2.right
if stack2 != None and len(stack2) >0:
return False
return True