迭代法几乎是二叉树和有向序列的通用解法。
比如,求二叉树的遍历,深度,最大值问题,求有向序列的合并等。
![](https://img.haomeiwen.com/i11633741/65f00d601ca11c66.png)
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
elif l2 is None:
return l1
else:
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l2, l1.next)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
网友评论