码迷,mamicode.com
首页 > 其他好文 > 详细

#Leet Code# Populating Next Right Pointers in Each Node II

时间:2014-08-01 19:15:42      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   代码   div   

描述:注意需要先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.left
10                 break
11             else:
12                 conNode.next = nextNode.right
13                 break
14 
15     def connect(self, root):
16         if root is None:
17             return
18 
19         if root.left is None and root.right is None:
20             return
21         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.right
27             self.doSth(root.next, root.right)
28 
29         
30         self.connect(root.right)
31         self.connect(root.left)

 

#Leet Code# Populating Next Right Pointers in Each Node II,布布扣,bubuko.com

#Leet Code# Populating Next Right Pointers in Each Node II

标签:style   blog   color   os   io   ar   代码   div   

原文地址:http://www.cnblogs.com/mess4u/p/3885438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!