Height-balanced tree understanding zero input test case - python

I'm trying to solve one algorithmic problem from leetcode.
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node
never differ by more than 1.
My approach is to collect the depths of the nodes and compare them. When the difference is smaller than 1 (abs), then return 1, else return False. When there is not root replace it with 0.
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root or not root.left and not root.right:
return 0
a = self.isBalanced(root.left)
b = self.isBalanced(root.right)
if abs(a-b)<=1:
return 1 + max(a,b)
else:
return False
return True
Unfortunately, the solution fails on a very primitive [] empty test input. Which is unclear to me. I thought that when there are no children, there's nothing to compare, hence 0. Am I missing smth from the definition of height-balanced tree?

Related

Search in Binary Search Tree - why this code works?

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.

Question about returning the right thing from recursive function (Leetcode 572)

I am doing Leet Code question 572. Subtree of Another Tree:
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
I had a working solution. However, when trying a slightly different approach, I ran into a problem with my recursive dfs function. The structure of my code is this:
def isSubTree(self, root, subRoot):
def dfs(root, subRoot):
# some function that returns True when certain conditions are met
if not root: return
self.isSubtree(root.left, subRoot)
self.isSubtree(root.right, subRoot)
if root.val == subRoot.val:
if dfs(root, subRoot):
return True
return False
Basically, isSubTree explores all the nodes in the tree. Once it finds a node with the same value as subRoot, it compares the sub tree rooted at that node with the sub tree rooted at subRoot with dfs().
I intended that when the dfs() function returns true, isSubTree() will also return true. If I've explored all the nodes in the tree (isSubTree() reaches the end) and dfs() hasn't returned true
at all, isSubTree() will return False.
However,my code always returns false seemingly because of the last line where it returns False (I've tested it and can verify that the return True part in if dfs() was reached, also I'm pretty sure my dfs() function is correct).
My question is, is there an elegant way to have my code do what I want it to do?
It is hard to see which code you are using, since obviously there is a syntax problem just below def dfs. Either the indentation is off or there is code missing (at the time of writing).
There are these issues:
The returned value from either recursive self.isSubTree calls is not used at all. This cannot be right, as certainly you need that information to conclude anything about the work done.
if not root: return will not return a boolean value when it kicks in. This should make the distinction between the case where also subTree is None: in that case the returned value should be True. Otherwise it should be False
Assuming your non-provided dfs code is correct, it will deal well with the previous point as well (where one or both of the arguments is None), and will compare the node values correctly, so then if not root should not be performed before dfs is called, as dfs will take care of that.
Similarly if root.val == subTree.val should not have to occur where it now occurs, but only in dfs.
Concluding, the working code could be like this:
class Solution(object):
def isSubtree(self, root, subRoot):
def dfs(root, subRoot):
if not root or not subRoot or root.val != subRoot.val:
return root == subRoot # Must both be None to have success
return dfs(root.left, subRoot.left) and dfs(root.right, subRoot.right)
return dfs(root, subRoot) or root and (
self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
)
Solved it with the following:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def dfs(r1, r2):
# some function
if not root:
return False
if root.val == subRoot.val:
if dfs(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)

Wrong Answer in 'Is this a Binary Search Tree' on HackerRank

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)

what is wrong with my binary search tree validation code?

According to the definition, a Binary Tree must satisfy the following conditions:
1. The left subtree of a node contains only nodes with keys less than
the the node's key.
2. The right subtree of a node contains only nodes with keys greater than the node's key.
3. Both the left and right subtrees must also be binary search trees.
My code is returning True for the input [10 ,5, 15, #, #, 6, 20] but it's incorrect, it must return False.
The input follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here is the tree:
10
/ \
5 15
/ \
6 20
Here is my code :
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def isValidBST(self, root)
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
else:
if root.left and root.right:
return root.left.val < root.val < root.right.val and \
self.isValidBST(root.left) and self.isValidBST(root.right)
elif root.left and not root.right:
return root.left.val < root.val and self.isValidBST(root.left)
elif root.right and not root.left:
return root.right.val > root.val and self.isValidBST(root.right)
else:
return True
Consider a BST where A is the root value, B is the value at the root of its left subtree, and C is the value at the root of the right subtree under that. Your code will verify that A > B, and that B < C. But it does not check to see if A > C.
Or, from your example: It checks that 5<10, 10<15, 6<15, and 15<20, but does not check that 6>10.
Recall that the definition of a BST talks about all nodes in a subtree, not just the root.
Your algorithm doesn't implement frist two conditions properly. You should compare root value with maximum of left subtree and minimum of right subtree.
Alternatively, you can do an inorder traversal of the tree which should be in ascending order in binary search tree.

Determine if a binary tree rooted at a node is a max-heap [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I'm trying to determine if a binary tree rooted at a node is a max-heap, and to do so I followed the rules of the heap property for a max-heap which states:
Max-heap:
All nodes are either greater than or equal to each of its children
My Idea of the implementation:
If at the node given as the parameter of is_max_heap has no right or left node than return True
Otherwise, if the value of the node is greater than the value of the left and right node, then call the function again on both the right and left nodes.
Return False otherwise.
My code:
class BTNode:
'''A generic binary tree node.'''
def __init__(self, v):
'''(BTNode, int) -> NoneType
Initialize a new BTNode with value v.
'''
self.value = v
self.left = None
self.right = None
def is_max_heap(node):
'''(BTNode) -> bool
Return True iff the binary tree rooted at node is a max-heap
Precondition: the tree is complete.
'''
if node.left and node.right is None:
return True
else:
if node.value > node.left.value and node.value > node.right.value:
return is_max_heap(node.left) and is_max_heap(node.right)
else:
return False
if __name__ == '__main__':
l1 = BTNode(7)
l2 = BTNode(6)
l3 = BTNode(8)
l1.left = l2
l1.right = l3
print(is_max_heap(l1))
So, under if __name__ == '__main__': I created three nodes, with values, 7, 6, and 8. The first node has a left and right node. So the tree would look like this:
7
/ \
6 8
This does not satisfy the max-heap property so it should return False. However running my code returns True and I can't figure out where I might of went wrong. If anyone can help me that would be really appreciated.
You have not thought of the case when there is only one child. Make sure your program works right on these two trees, too - one is a min heap, the other is a max heap:
2 1
/ /
1 2
Also learn to set brackets correctly; you have made the classic mistake True and 42 == 42; which is True.
Consider handling the two maybe-nonexistant childs the same way.
if left is not None:
if not <check max heap property for left subtree>: return False
if right is not None:
if not <check max heap property for right subtree>: return False
return True
The missing function should compare to the current node and recurse into the subtree if necessary.

Categories