File tree 2 files changed +110
-0
lines changed
lectures/20-trees/code/Advance questions 2 files changed +110
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class DoubleLinkedList {
2
+ LLNode head ;
3
+ LLNode tail ;
4
+
5
+ public TreeNode convert (TreeNode root ) {
6
+ if (root == null ) {
7
+ return null ;
8
+ }
9
+
10
+ helper (root );
11
+
12
+ return head ;
13
+ }
14
+
15
+ private void helper (TreeNode node ) {
16
+ if (node == null ) {
17
+ return null ;
18
+ }
19
+
20
+ helper (node .left );
21
+
22
+
23
+ LLNode newNode = new LLNode (node .val );
24
+
25
+ if (head == null ) {
26
+ head = newNode ;
27
+ tail = newNode ;
28
+ } else {
29
+ tail .next = newNode ;
30
+ newNode .prev = tail ;
31
+ tail = newNode ;
32
+ }
33
+
34
+ helper (node .right );
35
+
36
+ }
37
+ }
38
+
39
+ class LLNode {
40
+ int val ;
41
+ LLNode prev ;
42
+ LLNode next ;
43
+
44
+ public LLNode (int val ) {
45
+ this .val = val ;
46
+ }
47
+ }
48
+
49
+ class TreeNode {
50
+ int val ;
51
+ TreeNode left ;
52
+ TreeNode right ;
53
+
54
+ public TreeNode (int val ) {
55
+ this .val = val ;
56
+ }
57
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ class Node {
4
+ int val ;
5
+ Node left ;
6
+ Node right ;
7
+ public Node (int val ) {
8
+ this .val = val ;
9
+ }
10
+ }
11
+
12
+ public class TwoNodeSwap {
13
+ Node first ;
14
+ Node second ;
15
+ Node prev ;
16
+
17
+ public void helper (Node root ) {
18
+ iot (root );
19
+
20
+ // swap
21
+ int temp = first .val ;
22
+ first .val = second .val ;
23
+ second .val = temp ;
24
+ }
25
+
26
+ private void iot (Node node ) {
27
+ if (node == null ) {
28
+ return ;
29
+ }
30
+
31
+ iot (node .left );
32
+
33
+ if (prev != null && prev .val > node .val ) {
34
+ if (first == null ) {
35
+ first = prev ;
36
+ }
37
+ second = node ;
38
+ }
39
+
40
+ prev = node ;
41
+
42
+ iot (node .right );
43
+ }
44
+
45
+ public void printIOT (Node node ) {
46
+ if (node == null ) {
47
+ return ;
48
+ }
49
+ printIOT (node .left );
50
+ System .out .print (node .val + " " );
51
+ printIOT (node .right );
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments