File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
solution/1000-1099/1028.Recover a Tree From Preorder Traversal Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 69
69
70
70
<!-- tabs:start -->
71
71
72
+ #### Java
73
+
74
+ ``` java
75
+ /**
76
+ * Definition for a binary tree node.
77
+ * public class TreeNode {
78
+ * int val;
79
+ * TreeNode left;
80
+ * TreeNode right;
81
+ * TreeNode() {}
82
+ * TreeNode(int val) { this.val = val; }
83
+ * TreeNode(int val, TreeNode left, TreeNode right) {
84
+ * this.val = val;
85
+ * this.left = left;
86
+ * this.right = right;
87
+ * }
88
+ * }
89
+ */
90
+ class Solution {
91
+ public TreeNode recoverFromPreorder (String traversal ) {
92
+ Stack<TreeNode > stack = new Stack<> ();
93
+ int i = 0 ;
94
+
95
+ while (i < traversal. length()) {
96
+ int depth = 0 ;
97
+ while (i < traversal. length() && traversal. charAt(i) == ' -' ) {
98
+ depth++ ;
99
+ i++ ;
100
+ }
101
+
102
+ int num = 0 ;
103
+ while (i < traversal. length() && Character . isDigit(traversal. charAt(i))) {
104
+ num = num * 10 + (traversal. charAt(i) - ' 0' );
105
+ i++ ;
106
+ }
107
+
108
+ // Create the new node
109
+ TreeNode newNode = new TreeNode (num);
110
+
111
+ while (stack. size() > depth) {
112
+ stack. pop();
113
+ }
114
+ if (! stack. isEmpty()) {
115
+ if (stack. peek(). left == null ) {
116
+ stack. peek(). left = newNode;
117
+ } else {
118
+ stack. peek(). right = newNode;
119
+ }
120
+ }
121
+
122
+ stack. push(newNode);
123
+ }
124
+ return stack. isEmpty() ? null : stack. get(0 );
125
+ }
126
+ }
127
+ ```
128
+
72
129
#### C++
73
130
74
131
``` cpp
You can’t perform that action at this time.
0 commit comments