如何解决为什么“ while lenx”给出正确答案,而“ while x”给出超过时限?
给出一个二叉树,连接相同级别的节点。您将获得一个相同的nextRight指针。
最初,所有nextRight指针都指向垃圾值。您的函数应将这些指针设置为指向每个节点的下一个右指针。
10 10 ------> NULL
/ \ / \
3 5 => 3 ------> 5 --------> NULL
/ \ \ / \ \
4 1 2 4 --> 1 -----> 2 -------> NULL
我的代码:
def connect(root):
q = []
q.append(root)
while q:
x = len(q)
for i in range(x):
curr_node = q[0]
if i!=x-1:
curr_node.nextRight = q[1]
if curr_node.left:
q.append(curr_node.left)
if curr_node.right:
q.append(curr_node.right)
q.pop(0)
'''
:param root: root of the given tree
:return: none,just connect accordingly.
{
# Node Class:
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
self.nextRight = None
}
请注意,当我使用while q
时,我已经超过了时间限制;当我使用while len(q)
时,我得到了正确的答案。谁能告诉我为什么如此?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。