问题描述
给出一个二叉树,连接相同级别的节点。您将获得一个相同的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 (将#修改为@)