File tree 2 files changed +75
-0
lines changed 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int [] sumZero (int n ) {
3
+ int [] arr = new int [n ];
4
+ int idx = 0 ;
5
+ int num = n / 2 ;
6
+ while (idx < n / 2 ) {
7
+ arr [idx ++] = num * -1 ;
8
+ num --;
9
+ }
10
+ if (n % 2 != 0 ) {
11
+ arr [idx ++] = 0 ;
12
+ }
13
+ num = n / 2 ;
14
+ while (idx < n ) {
15
+ arr [idx ++] = num ;
16
+ num --;
17
+ }
18
+ return arr ;
19
+ }
20
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode(int x) { val = x; }
8
+ * }
9
+ */
10
+ class Solution {
11
+ List <Integer > ans ;
12
+ public List <Integer > getAllElements (TreeNode root1 , TreeNode root2 ) {
13
+ ans = new ArrayList <>();
14
+ helper (root1 , root2 );
15
+ return ans ;
16
+ }
17
+
18
+ private void helper (TreeNode r1 , TreeNode r2 ) {
19
+ Stack <TreeNode > stack1 = new Stack <>();
20
+ Stack <TreeNode > stack2 = new Stack <>();
21
+ addToStack (stack1 , r1 );
22
+ addToStack (stack2 , r2 );
23
+ while (!stack1 .isEmpty () || !stack2 .isEmpty ()) {
24
+ TreeNode popped1 = stack1 .isEmpty () ? null : stack1 .pop ();
25
+ TreeNode popped2 = stack2 .isEmpty () ? null : stack2 .pop ();
26
+ if (popped1 != null && popped2 != null ) {
27
+ if (popped1 .val > popped2 .val ) {
28
+ ans .add (popped2 .val );
29
+ addToStack (stack2 , popped2 .right );
30
+ stack1 .push (popped1 );
31
+ }
32
+ else {
33
+ ans .add (popped1 .val );
34
+ addToStack (stack1 , popped1 .right );
35
+ stack2 .push (popped2 );
36
+ }
37
+ }
38
+ else if (popped2 == null ) {
39
+ ans .add (popped1 .val );
40
+ addToStack (stack1 , popped1 .right );
41
+ }
42
+ else {
43
+ ans .add (popped2 .val );
44
+ addToStack (stack2 , popped2 .right );
45
+ }
46
+ }
47
+ }
48
+
49
+ private void addToStack (Stack <TreeNode > stack , TreeNode node ) {
50
+ while (node != null ) {
51
+ stack .push (node );
52
+ node = node .left ;
53
+ }
54
+ }
55
+ }
You can’t perform that action at this time.
0 commit comments