Same Tree
题目
给予两棵二叉树,判断这两棵树是否相等(即各节点的值都一样)
解题思路
分别遍历两棵二叉树,并用列表分别存储这两棵树的节点的值,比较这两个列表就可以了
class Solution:
# @param {TreeNode} p
# @param {TreeNode} q
# @return {boolean}
def isSameTree(self, p, q):
if (not p) and (not q):
return True
if (not p) and q:
return False
if (not q) and p:
return False
plist = self.pTree(p)
qlist = self.qTree(q)
if plist != qlist:
return False
return True
def pTree(self, root):
queue = []
plist = []
plist.append(root.val)
queue.append(root)
while queue:
root = queue.pop(0)
if root.left:
queue.append(root.left)
plist.append(root.left.val)
if not root.left:
plist.append('null')
if root.right:
queue.append(root.right)
plist.append(root.right.val)
if not root.right:
plist.append('null')
return plist
def qTree(self, root):
queue = []
qlist = []
qlist.append(root.val)
queue.append(root)
while queue:
root = queue.pop(0)
if root.left:
queue.append(root.left)
qlist.append(root.left.val)
if not root.left:
qlist.append('null')
if root.right:
queue.append(root.right)
qlist.append(root.right.val)
if not root.right:
qlist.append('null')
return qlist