-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path114.flatten-binary-tree-to-linked-list.java
More file actions
91 lines (84 loc) · 2.29 KB
/
Copy path114.flatten-binary-tree-to-linked-list.java
File metadata and controls
91 lines (84 loc) · 2.29 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
/*
* @lc app=leetcode id=114 lang=java
*
* [114] Flatten Binary Tree to Linked List
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// Iterative解法 Space O(1)
public void flatten(TreeNode root) {
if (root == null) {
return;
}
while (root != null) {
if (root.left != null) {
TreeNode leftTail = root.left;
while (leftTail.right != null) {
leftTail = leftTail.right;
}
leftTail.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
// public void flatten(TreeNode root) {
// flattenTree(root);
// }
// private TreeNode flattenTree(TreeNode root) {
// if (root == null) {
// return root;
// }
// if (root.left == null && root.right == null) {
// return root;
// }
// TreeNode leftTail = flattenTree(root.left);
// TreeNode rightTail = flattenTree(root.right);
// if (leftTail != null) {
// leftTail.right = root.right;
// root.right = root.left;
// root.left = null;
// }
// if (rightTail != null) {
// return rightTail;
// }
// else {
// return leftTail;
// }
// }
// public void flatten(TreeNode root) {
// if (root == null) {
// return;
// }
// if (root.left == null && root.right == null) {
// return;
// }
// flatten(root.left);
// flatten(root.right);
// TreeNode preRightNode = root.right;
// root.right = root.left;
// root.left = null;
// // Find Left child Tail
// while (root.right != null) {
// root = root.right;
// }
// root.right = preRightNode;
// }
}
// @lc code=end