forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlatten Binary Tree to Linked List.java
More file actions
90 lines (59 loc) · 1.38 KB
/
Copy pathFlatten Binary Tree to Linked List.java
File metadata and controls
90 lines (59 loc) · 1.38 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
E
Not Done
```
/*
Flatten Binary Tree to Linked List
Flatten a binary tree to a fake "linked list" in pre-order traversal.
Here we use the right pointer in TreeNode as the next pointer in ListNode.
Example
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
Note
Don't forget to mark the left child of each node to null.
Or you will get Time Limit Exceeded or Memory Limit Exceeded.
Challenge
Do it in-place without any extra memory.
Tags Expand
Binary Tree Depth First Search
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public TreeNode parentNode = null;
public void flatten(TreeNode root) {
if (root == null) {
return;
}
if (parentNode != null) {
parentNode.left = null;
parentNode.right = root;
}
parentNode = root;
TreeNode right = root.right;
flatten(root.left);
flatten(right);
}
}
```