I am going to compare Binary Tree in Golang.But my answer is wrong. Need the third eye to help.
Thanks.
package main
import(
"fmt"
)
type TreeNode struct {
val int
left *TreeNode
right *TreeNode
}
func isSameTree(p *TreeNode , q *TreeNode ) (bool){
if p == nil && q == nil {
return true
}
if p != nil && q == nil{
return false;
}
if p ==nil && q != nil {
return false;
}
if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.left)){
return true;
} else {
return false;
}
}
func main(){
p := &TreeNode{val: 1}
p.left = &TreeNode{val: 2}
p.right = &TreeNode{val: 3}
q := &TreeNode{val: 1}
q.left = &TreeNode{val: 2}
q.right = &TreeNode{val: 3}
isSame := isSameTree(p,q)
fmt.Println("is same?: ", isSame)
}
Go playground link for this code:
https://play.golang.org/p/mTX3aBxh6_
This line has a small mistake;
if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.left)){
It should be;
if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.right)){
If you don't see the difference in the second call to isSameTree you're passing q.left when it is supposed to be q.right.
Updated go play; https://play.golang.org/p/ul9ijG9HLc
Related
Q: Given the roots of two binary trees p and q, write a function to check if they are the same or not.
solution:
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// p and q are both null
if (p == null && q == null) return true;
// one of p and q is null
if (q == null || p == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.right, q.right) &&
isSameTree(p.left, q.left);
}
}
I am confused about the "return isSameTree(p.right, q.right) &&
isSameTree(p.left, q.left);" what is the meaning of it, and why there is no condition like "else" before it ??? what it return finally ?
I'm trying to compare list of music with releaseDate. But I can retrieve music without releaseDate and when I want to sort them, I got an error.
How can I sort / compare nullable datetime and put null releaseDate to the end?
_followedMusic.sort((a, b) {
if (a.releaseDate != null && b.releaseDate != null)
return a.releaseDate.compareTo(b.releaseDate);
else
// return ??
});
Thank you
If you take a look at the documentation for compareTo:
Returns a value like a Comparator when comparing this to other. That is, it returns a negative integer if this is ordered before other, a positive integer if this is ordered after other, and zero if this and other are ordered together.
https://api.dart.dev/stable/2.10.0/dart-core/Comparable/compareTo.html
So your compareTo should just result in returning the values -1, 0 or 1 according to if the compared object should be before, the same position or after the current object.
So in your case if you want your null entries to be at the start of the sorted list, you can do something like this:
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return -1;
} else if (s2 == null) {
return 1;
} else {
return s1.compareTo(s2);
}
});
print(list); // [null, null, a, b, c]
}
Or if you want the null at the end:
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return 1;
} else if (s2 == null) {
return -1;
} else {
return s1.compareTo(s2);
}
});
print(list); // [a, b, c, null, null]
}
Or, as #lrn suggests, make the last example in a more short and efficient way (but maybe not as readable :) ):
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) => s1 == null
? s2 == null
? 0
: 1
: s2 == null
? -1
: s1.compareTo(s2));
print(list); // [a, b, c, null, null]
}
what about _followdMusic.map((date) => return date ?? 1900.01.01).toList().sort(...)
the date is pseudo code, not sure how to write it. This way you put all unknown dates at one of the ends of the list.
The answer of #julemand101 also can be used with the extension function.
extension DateEx on DateTime? {
int compareToWithNull(DateTime? date2) {
if (this == null && date2 == null) {
return 0;
} else if (this == null) {
return -1;
} else if (date2 == null) {
return 1;
} else {
return this!.compareTo(date2);
}
}
}
I have a function that takes a pointer to any slice, and said parameter is of type interface{}.
I need to make sure that the pointer does not point to a nil slice.
package main
import (
"fmt"
)
type Dog struct {
Name string
Age int
}
func main() {
var slicePointer interface{}
// We only want slices that were initialized with `make()`.
dogs1 := make([]Dog, 0)
fmt.Println("dogs1 == nil:", dogs1 == nil)
slicePointer = &dogs1
fmt.Println("slicePointer == nil:", slicePointer == nil)
fmt.Println("-----")
// This needs to be caught, as the slice is `nil`.
var dogs2 []Dog
fmt.Println("dogs2 == nil:", dogs2 == nil)
slicePointer = &dogs2
fmt.Println("slicePointer == nil:", slicePointer == nil)
}
Output:
dogs1 == nil: false
slicePointer == nil: false
-----
dogs2 == nil: true
slicePointer == nil: false
Is there a way to do such a check in Golang?
You can tell if a non-nil interface has a nil-pointer value using reflection:
fmt.Println(reflect.ValueOf(slicePointer).Elem().IsNil())
For the safest approach:
if slicePointer!=nil {
v:=reflect.ValueOf(slicePointer)
if v.Kind()==reflect.Ptr {
fmt.Println(v.Elem().IsNil())
}
}
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).
package main
import "fmt"
func main() {
x := []int{1, 2, 3}
fmt.Println(len2(x))
}
func len2(s []int) int {
if s == nil {
return 0
}
return 1 + len2(s[1:])
}
the result it should be in this example '3'.
It's broken in if s == nil:
panic: runtime error: slice bounds out of range
It panics because you have no valid termination condition.
When your len2() is called with a non-nil empty slice, it attempts to slice it like s[1:], which will be a runtime panic.
Instead of checking for nil slice, check if the slice is empty by comparing its length to 0:
func len2(s []int) int {
if len(s) == 0 {
return 0
}
return 1 + len2(s[1:])
}
Try it on the Go Playground.
If you can't use the builtin len() function (which you already did in your solution), you may use the for ... range:
func len2(s []int) int {
size := 0
for i := range s {
size = i + 1
}
return size
}
Try this on the Go Playground.
And if it must be recursive, then for example:
func len2(s []int) int {
size := 0
for range s {
size = 1 + len2(s[1:])
break
}
return size
}
Try this on the Go Playground.
But know that these are awful solutions compared to using the builtin len().
The following is not a solution with better performance than len but an implementation that does not use any extra libraries and depends on recursion to find length
func len2(s []int) (count int) {
defer func() {
if r := recover(); r != nil {
count = 0
}
}()
return 1 + len2(s[1:])
}
Here is sample code
package main
import "fmt"
func main() {
var x []int = nil
var x1 = []int{1, 2, 3, 4}
var x2 = []int{}
var x3 = make([]int, 10, 20)
fmt.Println(len2(x))
fmt.Println(len2(x1))
fmt.Println(len2(x2))
fmt.Println(len2(x3))
}
func len2(s []int) (count int) {
defer func() {
if r := recover(); r != nil {
count = 0
}
}()
return 1 + len2(s[1:])
}
Checkout the same in playground
If you can leave without recursion here is a function that does not use len() and should be faster then re-slicing recursively.
func len2(s []int) (count int) {
for i := range s {
count = i + 1
}
}
If you do not want to use len() func, you can use cap()
func main() {
x := []int{1, 2, 3}
fmt.Println(len2(x))
}
func len2(s []int) int {
if cap(s) == 0 {
return 0
}
return 1 + len2(s[1:])
}
Try it again
Original Answer:
In order to check if an array (slice) is empty, you should use the function len()
if len(s) == 0 {
return 0
}
Try it
what is the base case here ?? This is fully functional but how it's working?
int isPali(char *s, int l, int r)
{
return ((l == r) || (s[l] == s[r] && isPali(s, l+1, r-1)));
}
int main()
{
char str[100];
scanf("%s", str);
if(isPali(str, 0, strlen(str)-1))
printf("Palindrome\n");
else
printf("Not palindrome\n");
}
It's in the only line of the function. Remember short-circuit logic in evaluating expressions. The or can be changed to
if (l == r)
return True;
else
return (s[l] == s[r] && isPali(s, l+1, r-1));
Of course, you can now apply the short-circuit to that else part:
else
if s[l] == s[r]
return isPali(s, l+1, r-1);
else
return False;