Skip to content

Commit 2aad026

Browse files
committed
Reorder List/ Binary Tree Preorder Traversal
1 parent f76cfd3 commit 2aad026

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

143 Reorder List.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
3+
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
4+
5+
You must do this in-place without altering the nodes' values.
6+
7+
For example,
8+
Given {1,2,3,4}, reorder it to {1,4,2,3}.
9+
'''
10+
11+
# Definition for singly-linked list.
12+
class ListNode(object):
13+
def __init__(self, x):
14+
self.val = x
15+
self.next = None
16+
17+
18+
class Solution(object):
19+
def reorderList(self, head):
20+
"""
21+
:type head: ListNode
22+
:rtype: void Do not return anything, modify head in-place instead.
23+
"""
24+
if not head:
25+
return
26+
# split
27+
fast = slow = head
28+
while fast and fast.next:
29+
slow = slow.next
30+
fast = fast.next.next
31+
head1, head2 = head, slow.next
32+
slow.next = None
33+
# reverse
34+
cur, pre = head2, None
35+
while cur:
36+
nex = cur.next
37+
cur.next = pre
38+
pre = cur
39+
cur = nex
40+
# merge
41+
cur1, cur2 = head1, pre
42+
while cur2:
43+
nex1, nex2 = cur1.next, cur2.next
44+
cur1.next = cur2
45+
cur2.next = nex1
46+
cur1, cur2 = nex1, nex2
47+
48+
49+
if __name__ == "__main__":
50+
None

144 Binary Tree Preorder Traversal.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
Given a binary tree, return the preorder traversal of its nodes' values.
3+
4+
For example:
5+
Given binary tree {1,#,2,3},
6+
1
7+
\
8+
2
9+
/
10+
3
11+
return [1,2,3].
12+
13+
Note: Recursive solution is trivial, could you do it iteratively?
14+
'''
15+
16+
# Definition for a binary tree node.
17+
class TreeNode(object):
18+
def __init__(self, x):
19+
self.val = x
20+
self.left = None
21+
self.right = None
22+
23+
24+
class Solution(object):
25+
def preorderTraversal(self, root):
26+
"""
27+
:type root: TreeNode
28+
:rtype: List[int]
29+
"""
30+
stack = []
31+
result = []
32+
while root or stack:
33+
if not root:
34+
root = stack.pop()
35+
result.append(root.val)
36+
if root.right:
37+
stack.append(root.right)
38+
root = root.left
39+
return result
40+
41+
42+
if __name__ == "__main__":
43+
None

0 commit comments

Comments
 (0)