首页 > 代码库 > #Leet Code# Populating Next Right Pointers in Each Node II
#Leet Code# Populating Next Right Pointers in Each Node II
描述:注意需要先self.connect(right)再self.connect(left),否则会有case通不过,原因是左边递归执行时依赖与右边的next已经建立,而先执行connect(left)的话右边还没有完成关系的建立。
代码:
1 class Solution: 2 # @param root, a tree node 3 # @return nothing 4 def doSth(self, nextNode, conNode): 5 while nextNode is not None: 6 if nextNode.left is None and nextNode.right is None: 7 nextNode = nextNode.next 8 elif nextNode.left is not None: 9 conNode.next = nextNode.left10 break11 else:12 conNode.next = nextNode.right13 break14 15 def connect(self, root):16 if root is None:17 return18 19 if root.left is None and root.right is None:20 return21 elif root.left is None and root.right is not None:22 self.doSth(root.next, root.right)23 elif root.left is not None and root.right is None:24 self.doSth(root.next, root.left)25 else:26 root.left.next = root.right27 self.doSth(root.next, root.right)28 29 30 self.connect(root.right)31 self.connect(root.left)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。