如何解决检查二叉树是否围绕其中心对称 - 如何打印节点值作为调试?
我正在编写代码来解决以下 leetcode 问题: https://leetcode.com/problems/symmetric-tree/
简而言之,问题是“给定二叉树的根,检查它是否是自身的镜像(即围绕其中心对称)。”
from collections import deque
class Solution:
def isSymmetric(self,root: TreeNode) -> bool:
queue= deque()
if not root:
return []
#add left and right child of root to start (if root is not None)
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
right_subt = []
left_subt = []
while queue:
level_length = len(queue)
#iterate over each level of the tree and add left subtree to left_subt and right subtree to right_subt
for _ in range((level_length//2)+1):
node = queue.popleft()
left_subt.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
for _ in range((level_length-(level_length//2))+1):
node = queue.popleft()
right_subt.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
#compare left and right subtree at each level to check if they're the same
if left_subt !=right_subt.reverse():
return False
#reinitialize left and right subtree lists
left_subt = []
right_subt = []
return True
我已经使用以下 input: [1,2,3,4,3]
运行了算法;当您点击上面的 Leetcode 链接时,它是您在页面顶部看到的输入。
它在应该返回 false
的时候却返回了 true
。当我在纸上运行输入时,它似乎有效,但与数组/字符串不同,我不确定如何在每个阶段 print
节点值。任何想法如何做到这一点,或者有人可以概述代码不足的地方?
解决方法
我不确定如何在每个阶段打印节点值。
在python中打印值就像:
print(<something>)
其中 <something>
是您需要打印的任何内容
出于调试目的,您可以在代码中的任何位置添加例如:
print(node.val)
或
print(queue)
,
至少以下代码片段不会像您预期的那样工作
for _ in range((level_length//2)+1):
node = queue.popleft()
left_subt.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
就在第一个循环处,此时 level_length == 2(假设 root.left 和 root.right 都不是 None )
-> (level_length//2)+1
将返回 (1 + 1)
-> 第一个 for 语句将循环两次,并在第二个 for 语句之前消耗 queue
中的 root.left 和 root.right开始
-> 你的 right_subt 什么都没有了
-> 在第二个 for 语句中, queue.popleft() 将抛出异常,因为您试图“从空双端队列中弹出”
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。