-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution114.java
More file actions
executable file
·40 lines (38 loc) · 1.09 KB
/
Copy pathSolution114.java
File metadata and controls
executable file
·40 lines (38 loc) · 1.09 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
/**
* 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 Solution114 {
public void flatten(TreeNode root) {
// 思路,将左边的树加在根节点与右子树中间
while (root != null) {
change(root, root.left);
root = root.right;
}
}
public void change(TreeNode father, TreeNode root){
TreeNode p = father.right;
// 当前节点的左子树不为空,递归合并
if (root != null && root.left != null) change(root, root.left);
if (root == null) return;
// 当前结点的左子树为空,直接合并
else {
father.left = null;
father.right = root;
while (root.right != null)
root = root.right;
root.right = p;
}
}
}