Last active
May 9, 2018 06:40
-
-
Save ashalva/615a08e830a55357250de053579388df to your computer and use it in GitHub Desktop.
Checking if the tree is binary or not in swift.
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
class Node { | |
var key : Int | |
var left : Node? | |
var right: Node? | |
init(key: Int, left: Node?, right: Node?) { | |
self.key = key | |
self.left = left | |
self.right = right | |
} | |
} | |
func isBST(tree: Node) -> Bool { | |
guard let left = tree.left, let right = tree.right else { | |
return true | |
} | |
print ("current: \(tree.key)") | |
print ("left: \(left.key) right: \(right.key)") | |
if left.key <= tree.key && right.key > tree.key { | |
if isBST(tree: left) && isBST(tree: right) { | |
return true | |
} else { | |
return false | |
} | |
} | |
return false | |
} | |
var secondLeftLeft = Node(key: 20, left: nil, right: nil) | |
var seconLeftRight = Node(key: 35, left: nil, right: nil) | |
var firstLeft = Node(key: 30, left:secondLeftLeft, right: seconLeftRight) | |
var secondRightRight = Node(key: 51, left:nil, right: nil) | |
var secondRightLeft = Node(key: 49, left:nil, right: nil) | |
var firstRight = Node(key: 50, left:secondRightLeft, right: secondRightRight) | |
var rootNode = Node(key: 40, left: firstLeft, right: firstRight ) | |
isBST(tree: rootNode) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment