Created
December 12, 2020 06:39
-
-
Save brugnara/f97285c35ce9da07bc079e689e593e6b to your computer and use it in GitHub Desktop.
Validate a BST using pointers with golang
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
/** | |
* Definition for a binary tree node. | |
* type TreeNode struct { | |
* Val int | |
* Left *TreeNode | |
* Right *TreeNode | |
* } | |
*/ | |
func loopBST(root *TreeNode) bool { | |
if root == nil { | |
return false | |
} | |
prev := -1 | |
first := true | |
return loop(root, &prev, &first) | |
} | |
func loop(leaf *TreeNode, prev *int, first *bool) bool { | |
if leaf == nil { | |
return true | |
} | |
if !loop(leaf.Left, prev, first) { | |
return false | |
} | |
if !*first && leaf.Val <= *prev { | |
return false | |
} | |
*first = false | |
*prev = leaf.Val | |
if !loop(leaf.Right, prev, first) { | |
return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment