【python/leetcode/M】Populating Next Right Pointers in Each Node
阿新 • • 發佈:2018-12-15
題目
基本思路
- 看到二叉樹我們就想到需要使用遞迴的思路了。
- 注意遞迴之外的細節:正是這些細節完成了實際的邏輯求解 我們以2號結點為例:為了繁衍next結點,僅需要處理兩種微觀情況:
case 1: 2 -> 3 :
Solution: root.left.next = root.right
case 2: 2 -> 5 -> 6:
Solution: root.right.next = root.next.left if root.next else None
2 -> 3
/ \ /
4->5->6
實現程式碼
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if root and root.left:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
else:
root.right.next = None
self.connect(root.left)
self. connect(root.right)