File tree 2 files changed +27
-38
lines changed 2 files changed +27
-38
lines changed Original file line number Diff line number Diff line change 12
12
* }
13
13
*/
14
14
public class Solution {
15
- public ArrayList <Integer > inorderTraversal (TreeNode A ) {
16
- ArrayList <Integer > arr = new ArrayList <>();
17
- Stack <TreeNode > stack = new Stack <>();
18
-
19
- if (A == null ) return arr ;
20
-
21
- while (true ) {
22
- if (A != null ) {
23
- stack .push (A );
24
- A = A .left ;
25
- }
26
- else {
27
- if (stack .isEmpty ()) {
28
- break ;
29
- }
30
- A = stack .pop ();
31
- arr .add (A .val );
32
- A = A .right ;
33
- }
34
- }
35
-
36
- return arr ;
15
+ public ArrayList <Integer > inorderTraversal (TreeNode A ) {
16
+ ArrayList <Integer > list = new ArrayList <>();
17
+ Stack <TreeNode > stack = new Stack <>();
18
+ while (A != null ) {
19
+ stack .push (A );
20
+ A = A .left ;
37
21
}
22
+ while (!stack .isEmpty ()) {
23
+ TreeNode removed = stack .pop ();
24
+ list .add (removed .val );
25
+ TreeNode right = removed .right ;
26
+ while (right != null ) {
27
+ stack .push (right );
28
+ right = right .left ;
29
+ }
30
+ }
31
+ return list ;
32
+ }
38
33
}
Original file line number Diff line number Diff line change 12
12
* }
13
13
*/
14
14
public class Solution {
15
- public TreeNode invertTree (TreeNode A ) {
16
- if (A == null ) return A ;
17
- swap (A );
18
- return A ;
19
- }
20
-
21
- public void swap (TreeNode root ) {
22
- if (root .left == null && root .right == null ) {
23
- return ;
24
- }
25
- TreeNode n1 = root .left ;
26
- root .left = root .right ;
27
- root .right = n1 ;
28
-
29
- if (root .left != null ) swap (root .left );
30
- if (root .right != null ) swap (root .right );
15
+ public TreeNode invertTree (TreeNode A ) {
16
+ if (A == null ) {
17
+ return null ;
31
18
}
19
+ TreeNode left = A .left ;
20
+ A .left = A .right ;
21
+ A .right = left ;
22
+ invertTree (A .left );
23
+ invertTree (A .right );
24
+ return A ;
25
+ }
32
26
}
You can’t perform that action at this time.
0 commit comments