File tree 2 files changed +81
-0
lines changed
2 files changed +81
-0
lines changed 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
+ public TreeNode recoverFromPreorder (String S ) {
12
+ Map <Integer , TreeNode > map = new HashMap <>();
13
+ int idx = 0 ;
14
+ int n = S .length ();
15
+
16
+ while (idx < n ) {
17
+ int level = 0 ;
18
+ StringBuilder sb = new StringBuilder ();
19
+
20
+ while (idx < n && S .charAt (idx ) == '-' ) {
21
+ level ++;
22
+ idx ++;
23
+ }
24
+
25
+ while (idx < n && Character .isDigit (S .charAt (idx ))) {
26
+ sb .append (S .charAt (idx ++));
27
+ }
28
+
29
+ TreeNode currNode = new TreeNode (Integer .parseInt (sb .toString ()));
30
+ map .put (level , currNode );
31
+ if (level > 0 ) {
32
+ TreeNode parent = map .get (level - 1 );
33
+ if (parent .left == null ) {
34
+ parent .left = currNode ;
35
+ }
36
+ else {
37
+ parent .right = currNode ;
38
+ }
39
+ }
40
+ }
41
+
42
+ return map .get (0 );
43
+ }
44
+ }
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
+ int numOfSteps ;
12
+ public int distributeCoins (TreeNode root ) {
13
+ numOfSteps = 0 ;
14
+ postorder (root );
15
+
16
+ return numOfSteps ;
17
+ }
18
+
19
+ private int postorder (TreeNode root ) {
20
+ if (root == null ) {
21
+ return 0 ;
22
+ }
23
+
24
+ int coin = postorder (root .left ) + postorder (root .right );
25
+
26
+ if (root .val == 0 ) {
27
+ coin += -1 ;
28
+ }
29
+ else {
30
+ coin += root .val - 1 ;
31
+ }
32
+
33
+ numOfSteps += Math .abs (coin );
34
+
35
+ return coin ;
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments