I am looking into the LeetCode problem Search in a Binary Search Tree:
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
[...]
Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
I am not sure why this code below will work in Python:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
#base case
if not root: return None
if root.val == val: return root
#recursion relation
if val > root.val:
return self.searchBST(root.right, val)
else:
return self.searchBST(root.left, val)
Specifically, in the question it says (1) if Tree is null, then we need to return [], (2) If value is not in the tree, we need to return null
Then for the line of code if not root: return None, does it cater to (1)? Aren’t we required to return []?
in the question it says (1) if Tree is null, then we need to return [], (2) If value is not in the tree, we need to return null
That is not entirely true. It says that we need to return null, but in the example it represents the output as [].
It is understandable that this leads to confusion, but it should be noted that LeetCode formats (serializes) the input and the output as lists (JSON notation), even though the actual input and output that your function deals with are not lists. The function gets a node instance as argument (or None), and the function is to return such a reference (or None).
The LeetCode framework takes care of conversion of the text-based input into a node reference before calling your function, and does the reverse when dealing with the value that your function returns. In particular, when your function returns None, that will serialise to [] -- which represents an empty tree.
Related
I am trying to understand below recursion function which says whether a particular node exists in a binary tree. I did my homework and got most of the recursion part but the last return statement (return root.value == value or inleft or inright) bothers me.
can someone please help me in understanding this method?
def existsInTree(self, root, value):
if root is None:
return False
else:
inleft = self.existsInTree(root.left, value)
inright = self.existsInTree(root.right, value)
print(inleft,inright)
return root.value == value or inleft or inright
example binary tree:
10
/ \
11 9
we will first compare data of root with data of node to be searched. If the match is found, set the flag to true. Else, search the node in left subtree and then in the right subtree.
There's another way of looking at that return statement, you can split the return statement at the or keyword
def ifRootExists(self,root, value):
if (root == None):
return False
if (root.value == value):
return True
""" then recur on left sutree """
res1 = ifrootExists(root.left, value)
# root found, no need to look further
if res1:
return True
""" root is not found in left,
so recur on right subtree """
res2 = ifrootExists(root.right, value)
return res2
We can get the result from the above function whether some node exists.
The algorithm is as follows.
root is None or Not. If None, get back the position which the parent function called with the value of "False".
Otherwise, the function continuously search based on the current node.
inleft is a value of function "existsInTree" in which the current node's left child is the root node.
inright is a value of function "existsInTree" in which the current node's right child is the root node.
Let's assume that we want to search value as called V.
Which V exists in the tree means the current value is V or in the left tree, or in the right tree.
To summarize, inleft and inright means whether V includes or not in the subtree.
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements:
The value of every node in a node's left subtree is less than the data value of that node.
The value of every node in a node's right subtree is greater than the data value of that node.
Given the root node of a binary tree, can you determine if it's also a binary search tree?
Complete the function in your editor below, which has parameter: a pointer to the root of a binary tree. It must return a boolean denoting whether or not the binary tree is a binary search tree. You may have to write one or more helper functions to complete this challenge.
Input Format
You are not responsible for reading any input from stdin. Hidden code stubs will assemble a binary tree and pass its root node to your function as an argument.
Constraints:
0<=data<=10^4
Output Format
You are not responsible for printing any output to stdout. Your function must return true if the tree is a binary search tree; otherwise, it must return false. Hidden code stubs will print this result as a Yes or No answer on a new line.
My Code:
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
if root is None or (root.left is None and root.right is None):
return True
if root.left.data>=root.data or root.right.data<=root.data:
return False
check_binary_search_tree_(root.left)
check_binary_search_tree_(root.right)
return True
Why am I getting Wrong Answer?
The problem with your code is
first you didn't do :
return check_binary_search_tree_(root.left) and check_binary_search_tree_(root.right)
next even if you do that, you are forgetting to keep the root's value in mind while checking the BST property for left and right children. It could be that your left child is totally a good BST but it fails to be a BST when you consider its parent. Look at the below example:
6
4 7
2 8
The subtree rooted at 4 is a good BST but fails when you consider its root's value of 6.
The solution is then to check the proper range of values at each node i.e.
left_limit < root.data < right_limit
You could write your function as :
def check_binary_search_tree_(root, min = -math.inf, max = math.inf):
if root is None:
return True
if root.data > min and root.data < max:
return check_binary_search_tree_(root.left, min, root.data) and check_binary_search_tree_(root.right, root.data, max)
return False
check_binary_search_tree_(root.left)
check_binary_search_tree_(root.right)
You don't return a result of these recursive functions. Try to do:
return check_binary_search_tree_(root.left) and check_binary_search_tree_(root.right)
Full code example that works:
def check_binary_search_tree_(root):
def isValid(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
if node.data <= lower or node.data >= upper:
return False
return isValid(node.left, lower, node.data) and isValid(node.right, node.data, upper)
return isValid(root)
I'm trying to build a BST (binary search tree) with dict in python. I do not understand why my code is not adding nodes to the BST. I saw a similar post here:
How to implement a binary search tree in Python?
which looks the same as my code except declaring a node class, but I would like to know why my dict implementation fails (and hopefully improve my understanding of parameter passing with recursion in python).
keys = [10,9,2,5,3,7,101,18]
start = {'key': keys[-1], 'val': 1, 'left': None, 'right': None}
def binarySearch(root, node):
# compare keys and insert node into right place
if not root:
root = node
elif node['key'] < root['key']:
binarySearch(root['left'], node)
else:
binarySearch(root['right'], node)
# Now let's test our function and build a BST
while keys:
key = keys.pop()
node = {'key': key, 'val': 1, 'left': None, 'right': None}
binarySearch(start, node)
print(start) # unchanged, hence my confusion. Thx for your time!
===========================================
Edit: here is the code that would make it work!
def binarySearch(root, node):
# compare keys and insert node into right place
if not root:
root = node
elif node['key'] < root['key']:
if not root['left']: root['left'] = node
else: binarySearch(root['left'], node)
else:
if not root['right']: root['right'] = node
else: binarySearch(root['right'], node)
Here is what I think that is happening under the hood (why one version is able to add to BST but the other one is not):
In the original version, we will reach a recursion call where root still points to None inside the BST, but then root = node make root points to node which has absolutely no connection with start, i.e. the BST itself. Then local variables are deleted and no changes are made.
In the modified version, we will avoid this since when we add the node by e.g. root['left'] = node. Here root is still pointing to the original BST and thus we are modifying the key-val pair in the original BST instead of having root point to something totally outside the BST.
Let's run through your code as though we were the python interpreter.
Lets start at the first call: binarySearch(start, node)
Here start is the dict defined at the top of your script and node is another dict (which curiously has the same value).
Lets jump inside the call and we find ourselves at: if not root: where root refers to start above and so is truthy so fails this if.
Next we find ourselves at: elif node['key'] < root['key']: which in this case is not True.
Next we pass into the else: and we are at: binarySearch(root['right'], node).
Just before we jump into the first recursive call, lets review what the parameters to the call are: root['right'] from start has the value None and node is still the same dict which we want to insert somewhere. So, onto the recursive call.
Again we find ourselves at: if not root:
However this time root just refers to the first parameter of the first recursive call and we can see from the above review of the parameters that root refers to None.
Now None is considered falsy and so this time the if succeeds and we are on to the next line.
Now we are at root = node.
This is an assignment in python. What this means is that python will use the variable root to stop referring to None and to refer to whatever node currently refers to, which is the dict which was created in the while loop. So root (which is just a parameter, but you can think of as a local variable now) refers to a dict.
Now what happens is that we are at the end of the first recursive call and this function ends. Whenever a function ends, all the local variables are destroyed. That is root and node are destroyed. That is just these variables and not what they refer to.
Now we return to just after the first call site i.e. just after binarySearch(root['right'], node)
We can see here that the parameters: root['right'], node still refer to whatever they were referring to before. This is why your start is unchanged and why your program should deal with left and right now instead of recursing.
#Creted by The Misunderstood Genius
def add_root(e,key):
''''
e is node's name
key is the node's key search
'''
bst=dict()
bst[e]={'key':key,'P':None,'L':None,'R':None}
return bst
def root(tree):
for k,v in tree.items():
if v['P'] == None:
return k
def insert(tree, node, key):
tree[node]={'key':key,'P':None,'L':None,'R':None}
y =None
x = root(tree)
node_key = tree[node]['key']
while x is not None:
y=x
node_root=tree['R']['key']
if node_key < node_root:
x=tree[x]['L']
else:
x=tree[x]['R']
tree[node]['P']=y
if y is not None and node_key< tree[y]['key']:
tree[y]['L']=node
else:
tree[y]['R']=node
return tree
def print_all(tree):
for k,v in tree.items():
print(k,v)
print()
'''
Give a root node and key search target
Returns the name of the node with associated key
Else None
'''
def tree_search(tree,root, target):
if root ==None:
print(" key with node associate not found")
return root
if tree[root]['key'] == target:
return root
if target < tree[root]['key']:
return tree_search(tree,tree[root]['L'],target)
else:
return tree_search(tree,tree[root]['R'],target)
def tree_iterative_search(tree,root,target):
while root is not None and tree[root]['key']!=target:
if target < tree[root]['key']:
root=tree[root]['L']
else:
root=tree[root]['R']
return root
def minimum(tree,root):
while tree[root]['L'] is not None:
root=tree[root]['L']
return tree[root]['key']
bst=add_root('R',20)
bst=insert(bst,'M',10)
bst=insert(bst,'B',8)
bst=insert(bst,'C',24)
bst=insert(bst,'D',22)
bst=insert(bst,'E',25)
bst=insert(bst,'G',25)
print_all(bst)
print(tree_search(bst,'R',25))
x=tree_iterative_search(bst,'R',25)
print(x)
#print(minimum(bst,'R'))
I got the following recursive function to compute the longest path of a binary tree. I'm new to recursive function, can someone help walk through how does this function derive the result = 4 with the given example?
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
lDepth = self.maxDepth(root.left)
rDepth = self.maxDepth(root.right)
if lDepth > rDepth:
return lDepth+1
else:
return rDepth+1
Recursive function is a function that calls itself. maxDepth is a function that is bound to the current node (root) of the tree and returns its depth.
In your case you are checking if your root has left or/and right leafs and calling their respective maxDepth functions, each time going one level deeper (down) into the tree.
Once you reach the lowest level (elements 4, -4 or 18) your root will be None, meaning you reached the deepest part of the tree. The depth of the deepest element is 0, hence we have the following code.
if root is None:
return 0
Now once you return this function, the return value is passed to the caller, which is the previous node. That means (4) will return its value to (3) which in turn will return to (2) and finally (5).
Each time the value is returned we will add + 1 to it before returning it again
if lDepth > rDepth:
return lDepth+1
else:
return rDepth+1
therefore (4) would return 0, (3): 1, (2): 2, (5): 3
When in doubt, you can print the respective lDepth,rDepth,root.left,root.right.
For this question it will evaluate the value topdown. Forgive my poor drawing.lol
When the recursive function maxDepth is called, a stack of function call is maintained. That'll continue until the basis step(root is None) is reached. Once the basis step is reached, the stack will be computed the order is was stored in reverse. For each subsequent roots basis step will be called and length will be returned. It'll end when there is no more roots to compute.
class EmptyMap():
"""
EmptyMap has no slots
"""
__slots__ = ()
class NonEmptyMap():
"""
Has slots of left, key, value, and right.
"""
__slots__ = ('left', 'key', 'value', 'right')
def mkEmptyMap():
"""
Is a function that takes no arguments and returns an instance of EmptyMap
"""
return EmptyMap()
def mkNonEmptyMap(left, key, value, right):
"""
Is a function that takes a map, a key, a value, and another map,
and returns an instance of NonEmptyMap. This function merely initializes the slots;
it is possible to use this function to create trees that are not binary search trees.
"""
nonEmptyMap = NonEmptyMap()
nonEmptyMap.left = left
nonEmptyMap.key = key
nonEmptyMap.value = value
nonEmptyMap.right = right
return nonEmptyMap
def mapInsert(key, value, node):
"""
Is a function that takes a key, a value, and a map, and returns an instance
of NonEmptyMap. Further, the map that is returned is a binary search tree based
on the keys. The function inserts the key-value pair into the correct position in the
map. The map returned need not be balanced. Before coding, review the binary
search tree definition and the structurally recursive design pattern, and determine
what the function should look like for maps. If the key already exists, the new value
should replace the old value.
"""
if isinstance(node, EmptyMap):
return mkNonEmptyMap(mkEmptyMap(), key, value, mkEmptyMap())
else:
if key > node.key:
node.right = mapInsert(key, value, node.right)
return node.right
elif key < node.key:
node.left = mapInsert(key, value, node.left)
return node.left
elif key == node.key:
node.value = value
return mapInsert(key, value, node)
else:
raise TypeError("Bad Tree Map")
def mapToString(node):
"""
Is a function that takes a map, and returns a string that represents the
map. Before coding, review the structurally recursive design pattern, and determine
how to adapt it for maps. An EmptyMap is represented as ’ ’. For an instance of
NonEmptyMap, the left sub-tree appears on the left, and the right sub-tree appears
on the right.
"""
if isinstance(node, EmptyMap):
return '_'
elif isinstance(node, NonEmptyMap):
return '(' + mapToString(node.left) + ',' + str(node.key) + '->' + str(node.value) + ',' + mapToString(node.right)+ ')'
else:
raise TypeError("Not a Binary Tree")
def mapSearch(key, node):
"""
Is a function that takes a key and a map, and returns the value associated
with the key or None if the key is not there. Before coding, review the binary search
tree definition and the structurally recursive design pattern, and determine how it
should look for maps.
"""
if isinstance(node, EmptyMap):
return 'None'
elif isinstance(node, NonEmptyMap):
if key == node.key:
return str(node.value)
elif key < node.key:
return mapSearch(key, node.left)
elif key > node.key:
return mapSearch(key, node.right)
else:
raise TypeError("Not a Binary Tree")
def main():
smallMap = mapInsert(\
'one',\
1,\
mapInsert(\
'two',\
2,\
mapInsert(\
'three',\
3,\
mkEmptyMap())))
print(smallMap.key)
print(smallMap.left.key)
print(smallMap.right.key)
main()
When I run the program, I got a syntax which I have no idea what I am doing wrong. I am pretty sure the emptymap has an object which is in mkNonEmptyMap function. This is my homework problem.
A map is a data structure that associates values with keys. One can search for a particular key to find its associated value. For example, the value 3 could be associated with the key ’three’.
one
Traceback (most recent call last):
File "/Users/USER/Desktop/test.py", line 113, in <module>
main()
File "/Users/USER/Desktop/test.py", line 110, in main
print(smallMap.left.key)
AttributeError: 'EmptyMap' object has no attribute 'key'
If you look at what's in smallMap, its left and right are both EmptyMaps. So of course smallMap.left.key isn't going to work—EmptyMaps don't have keys.
So, why is it wrong? Well, let's break that monster expression down into steps and see where it goes wrong:
>>> empty = mkEmptyMap()
>>> mapToString(empty)
'_'
>>> three = mapInsert('three', 3, mkEmptyMap())
>>> mapToString(three)
'(_,three->3,_)'
>>> two = mapInsert('two', 2, three)
>>> mapToString(two)
(_,two->2,_)
There's a problem. The two object has no left or right. What about three?
>>> mapToString(three)
(_,three->3,(_,two->2,_))
OK, so we do have a valid balanced tree—but it's not in the two object returned by mapInsert, it's in the three object that you passed in to mapInsert (which your original program isn't even keeping a reference to).
So, why is that happening? Is that valid? It depends on your design. If you want to mutate your arguments like this, it's perfectly reasonable to do so (although I suspect it's not what your teacher actually wanted—anyone who's trying to force you to write ML in Python like this probably wants you to use non-mutating algorithms…). But then you need to always return the root node. Your function is clearly trying to return the newly-created node whether it's the root or not. So, just fix that:
if key > node.key:
node.right = mapInsert(key, value, node.right)
return node # not node.right
And likewise for the other two cases. (I'm not sure why you were trying to call yourself recursively in the == case in the first place.)
If you do that, the code no longer has an error.
It doesn't seem to be actually balancing the tree correctly, but that's the next problem for you to solve.