- Same Tree
**思路:第一想到的是递归,DFS, 但是实在是不熟练,还是看答案做的题;但是答案看到人家的多个思路时,实在不能理解其中的用堆栈存储二叉树的思想。
先存右结点,再存左结点,这样可以先弹出左边的根结点,如果他还有子节点,继续存,遇到不同的结点就可以跳出返回了。
队列,先进先出,存到队尾,先出来的数据是队首的。
堆栈,先进后出,存到栈顶,先出来的数据是栈顶的。
pop()函数,append()函数,insert()函数,push()函数
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
return p == q
stack = [(p, q)]
while stack:
p, q = stack.pop()
if p == None and q == None:
continue
if p == None or q == None:
return False
if p.val == q.val:
stack.append((p.right, q.right))
stack.append((p.left, q.left))
else:
return False
return True
- Symmetric Tree
**思路:左边的左边和右边的右边;左边的右边和右边的左边,要相等;并且根节点的值要相等。此外,函数的定义问题,虽然是调用函数,但两者是并列关系,不要写错缩进关系了。
bool类型:True、False、None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# @param root, a tree node
# @return a boolean
def isSym(self,left,right):
if left == None and right == None:
return True
if left and right and left.val == right.val :
return self.isSym(left.left,right.right) and self.isSym(left.right,right.left)
else:
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
else :
return self.isSym(root.left,root.right)
网友评论