Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 2 3 4 5 |
1 / \ 2 5 / \ \ 3 4 6 |
The flattened tree should look like:
1 2 3 4 5 6 7 8 9 10 11 |
1 \ 2 \ 3 \ 4 \ 5 \ 6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
func flatten(_ root: TreeNode?) { if let p = root { flatten(p.left) flatten(p.right) if let l = p.left { if let r = p.right { var lr = l while lr.right != nil { lr = lr.right! } lr.right = r } p.right = l p.left = nil } } } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼