题解 | #二叉树中和为某一值的路径(一)#
对称的二叉树
http://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
利用广度优先遍历将节点的值压入栈,当遇到相等的值时弹栈,最后栈中午元素说明对称(注意空节点处理)
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
class Solution:
def isSymmetrical(self , pRoot: TreeNode) -> bool:
nodeQueue=[pRoot]
valStack=[]
if not pRoot:
return True
while len(nodeQueue)>0:
if nodeQueue[0].left:
nodeQueue.append(nodeQueue[0].left)
if len(valStack)>0 and nodeQueue[0].left.val==valStack[-1]:
valStack.pop()
else:
valStack.append(nodeQueue[0].left.val)
else:
if len(valStack)>0 and valStack[-1]=='#':
valStack.pop(-1)
else:
valStack.append('#')
if nodeQueue[0].right:
nodeQueue.append(nodeQueue[0].right)
if len(valStack)>0 and nodeQueue[0].right.val==valStack[-1]:
valStack.pop()
else:
valStack.append(nodeQueue[0].right.val)
else:
if len(valStack)>0 and valStack[-1]=='#':
valStack.pop(-1)
else:
valStack.append('#')
nodeQueue.pop(0)
if len(valStack)>0:
return False
else:
return True
# write code here