-
Notifications
You must be signed in to change notification settings - Fork 28
/
114.flatten-binary-tree-to-linked-list.kt
75 lines (73 loc) · 1.39 KB
/
114.flatten-binary-tree-to-linked-list.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* @lc app=leetcode id=114 lang=kotlin
*
* [114] Flatten Binary Tree to Linked List
*
* https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
*
* algorithms
* Medium (48.29%)
* Likes: 2761
* Dislikes: 330
* Total Accepted: 345.7K
* Total Submissions: 708.9K
* Testcase Example: '[1,2,5,3,4,null,6]'
*
* Given a binary tree, flatten it to a linked list in-place.
*
* For example, given the following tree:
*
*
* 1
* / \
* 2 5
* / \ \
* 3 4 6
*
*
* The flattened tree should look like:
*
*
* 1
* \
* 2
* \
* 3
* \
* 4
* \
* 5
* \
* 6
*
*
*/
// @lc code=start
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun flatten(root: TreeNode?): Unit {
var cur = root
while (cur != null) {
if (cur?.left != null) {
var p = cur?.left
while (p?.right != null) {
p = p?.right
}
p?.right = cur?.right
cur?.right = cur?.left
cur?.left = null
}
cur = cur?.right
}
}
}
// @lc code=end