|
33 | 33 | / \ / \ |
34 | 34 | 4->5->6->7 -> NULL |
35 | 35 | """ |
36 | | -# Definition for binary tree with next pointer. |
37 | | -# class TreeLinkNode: |
38 | | -# def __init__(self, x): |
39 | | -# self.val = x |
40 | | -# self.left = None |
41 | | -# self.right = None |
42 | | -# self.next = None |
43 | | - |
| 36 | +""" |
| 37 | +# Definition for a Node. |
| 38 | +class Node: |
| 39 | + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): |
| 40 | + self.val = val |
| 41 | + self.left = left |
| 42 | + self.right = right |
| 43 | + self.next = next |
| 44 | +""" |
44 | 45 | class Solution: |
| 46 | + def connect(self, root: 'Node') -> 'Node': |
| 47 | + if not root: |
| 48 | + return |
| 49 | + |
| 50 | + self.dfs(root) |
| 51 | + return root |
| 52 | + |
| 53 | + |
| 54 | + def dfs(self, root, next_node=None): |
| 55 | + if not root: |
| 56 | + return |
| 57 | + |
| 58 | + root.next = next_node |
| 59 | + self.dfs(root.left, root.right) |
| 60 | + self.dfs(root.right, root.next.left if root.next else None) |
| 61 | + |
| 62 | + |
| 63 | +class Solution1: |
| 64 | + def connect(self, root: 'Node') -> 'Node': |
| 65 | + if not root: |
| 66 | + return |
| 67 | + |
| 68 | + self.dfs(root) |
| 69 | + return root |
| 70 | + |
| 71 | + |
| 72 | + def dfs(self, root, parent=None): |
| 73 | + if not root: |
| 74 | + return |
| 75 | + |
| 76 | + cur = None |
| 77 | + while parent: |
| 78 | + parent.left.next = parent.right |
| 79 | + if not cur: |
| 80 | + cur = parent.right |
| 81 | + else: |
| 82 | + cur.next = parent.left |
| 83 | + cur = parent.right |
| 84 | + parent = parent.next |
| 85 | + |
| 86 | + self.dfs(root.left, root) |
| 87 | + |
| 88 | +class Solution2: |
| 89 | + def connect(self, root: 'Node') -> 'Node': |
| 90 | + if not root: |
| 91 | + return |
| 92 | + |
| 93 | + self.dfs(root) |
| 94 | + return root |
| 95 | + |
| 96 | + |
| 97 | + def dfs(self, root, next_node=None): |
| 98 | + if not root: |
| 99 | + return |
| 100 | + |
| 101 | + root.next = next_node |
| 102 | + |
| 103 | + n1 = root.right |
| 104 | + n2 = root.next.left if root.next else None |
| 105 | + n3 = root.next.right if root.next else None |
| 106 | + next_node = n1 or n2 or n3 |
| 107 | + if root.left: |
| 108 | + self.dfs(root.left, next_node) |
| 109 | + if root.right: |
| 110 | + if next_node == n1: |
| 111 | + next_node = n2 or n3 |
| 112 | + elif next_node == n2: |
| 113 | + next_node = n3 |
| 114 | + else: |
| 115 | + next_node = None |
| 116 | + self.dfs(root.right, next_node) |
| 117 | + |
| 118 | + |
| 119 | +class Solution3: |
45 | 120 | # @param root, a tree link node |
46 | 121 | # @return nothing |
47 | 122 | def connect(self, root): |
|
0 commit comments