-
Notifications
You must be signed in to change notification settings - Fork 187
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #559 from 0xff-dev/331
Add solution and test-cases for problem 331
- Loading branch information
Showing
4 changed files
with
90 additions
and
21 deletions.
There are no files selected for viewing
40 changes: 27 additions & 13 deletions
40
leetcode/301-400/0331.Verify-Preorder-Serialization-of-a-Binary-Tree/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 52 additions & 2 deletions
54
leetcode/301-400/0331.Verify-Preorder-Serialization-of-a-Binary-Tree/Solution.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,55 @@ | ||
package Solution | ||
|
||
func Solution(x bool) bool { | ||
return x | ||
import "strings" | ||
|
||
type pair331 struct { | ||
sharp, index int | ||
} | ||
|
||
func Solution(preorder string) bool { | ||
if preorder == "#" { | ||
return true | ||
} | ||
items := strings.Split(preorder, ",") | ||
l := len(items) | ||
if l < 3 { | ||
return false | ||
} | ||
pairs := make([]pair331, 0) | ||
for i := 0; i < l; i++ { | ||
if items[i] != "#" { | ||
pairs = append(pairs, pair331{index: i}) | ||
continue | ||
} | ||
last := len(pairs) - 1 | ||
if last == -1 { | ||
return false | ||
} | ||
if items[pairs[last].index] == "#" || pairs[last].sharp >= 2 { | ||
pairs = append(pairs, pair331{index: i}) | ||
continue | ||
} | ||
pairs[last].sharp++ | ||
} | ||
|
||
stack := []int{-1, -1} | ||
for _, pair := range pairs { | ||
if pair.sharp == 1 { | ||
stack = append(stack, pair.index) | ||
continue | ||
} | ||
if pair.sharp == 0 && items[pair.index] != "#" { | ||
stack = append(stack, pair.index, pair.index) | ||
continue | ||
} | ||
ll := len(stack) | ||
if ll == 0 { | ||
break | ||
} | ||
for ll >= 2 && stack[ll-1] != stack[ll-2] { | ||
ll-- | ||
} | ||
stack = stack[:ll-1] | ||
} | ||
return len(stack) == 1 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file added
BIN
+12.9 KB
leetcode/301-400/0331.Verify-Preorder-Serialization-of-a-Binary-Tree/pre-tree.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.