forked from ganjingcatherine/Lintcode_HighFreq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path649.binary-tree-flipping.java
More file actions
47 lines (39 loc) · 969 Bytes
/
649.binary-tree-flipping.java
File metadata and controls
47 lines (39 loc) · 969 Bytes
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
/**
* 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: the root of binary tree
* @return: new root
*/
private TreeNode newRoot = null;
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null) {
return null;
}
dfs(root);
return newRoot;
}
private void dfs(TreeNode root) {
if (root.left == null) {
newRoot = root;
return ;
}
dfs(root.left);
// flip
TreeNode flippedRoot = root.left;
flippedRoot.left = root.right;
flippedRoot.right = root;
// break the link
root.left = null;
root.right = null;
}
}