-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflattenBT.java
More file actions
37 lines (32 loc) · 985 Bytes
/
flattenBT.java
File metadata and controls
37 lines (32 loc) · 985 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
public class Solution {
public void flatten(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return;
flatten(root.left);
flatten(root.right);
if(root.left!=null) {
TreeNode temp=root.right;
root.right=root.left;
root.left=null;
TreeNode rightmost=root.right;
while(rightmost.right!=null)
rightmost=rightmost.right;
rightmost.right=temp;
}
}
}
public:
void flatten(TreeNode *root) {
if (!root) return;
TreeNode* left = root->left;
TreeNode* right = root->right;
if (left) {
root->right = left;
root->left = NULL;
TreeNode* rightmost = left;
while(rightmost->right) {rightmost = rightmost->right;}
rightmost->right = right; // point the right most to the original right child
}
flatten(root->right);
}