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 74
74
75
75
<!-- tabs:start -->
76
76
77
+ #### Java
78
+
79
+ ``` java
80
+ /**
81
+ * Definition for a binary tree node.
82
+ * public class TreeNode {
83
+ * int val;
84
+ * TreeNode left;
85
+ * TreeNode right;
86
+ * TreeNode() {}
87
+ * TreeNode(int val) { this.val = val; }
88
+ * TreeNode(int val, TreeNode left, TreeNode right) {
89
+ * this.val = val;
90
+ * this.left = left;
91
+ * this.right = right;
92
+ * }
93
+ * }
94
+ */
95
+ class Solution {
96
+ public TreeNode recoverFromPreorder (String traversal ) {
97
+ Stack<TreeNode > stack = new Stack<> ();
98
+ int i = 0 ;
99
+
100
+ while (i < traversal. length()) {
101
+ int depth = 0 ;
102
+ while (i < traversal. length() && traversal. charAt(i) == ' -' ) {
103
+ depth++ ;
104
+ i++ ;
105
+ }
106
+
107
+ int num = 0 ;
108
+ while (i < traversal. length() && Character . isDigit(traversal. charAt(i))) {
109
+ num = num * 10 + (traversal. charAt(i) - ' 0' );
110
+ i++ ;
111
+ }
112
+
113
+ // Create the new node
114
+ TreeNode newNode = new TreeNode (num);
115
+
116
+ while (stack. size() > depth) {
117
+ stack. pop();
118
+ }
119
+ if (! stack. isEmpty()) {
120
+ if (stack. peek(). left == null ) {
121
+ stack. peek(). left = newNode;
122
+ } else {
123
+ stack. peek(). right = newNode;
124
+ }
125
+ }
126
+
127
+ stack. push(newNode);
128
+ }
129
+ return stack. isEmpty() ? null : stack. get(0 );
130
+ }
131
+ }
132
+ ```
133
+
77
134
#### C++
78
135
79
136
``` cpp
You can’t perform that action at this time.
0 commit comments