Banana-Leopard/TASTY huggingface dataset:
# Program to find height of tree by Iteration Method
 
# A binary tree node
class Node:
     
    # Constructor to create new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Iterative method to find height of Binary Tree
def treeHeight(root):
     
    # Base Case
    if root is None:
        return 0
     
    # Create a empty queue for level order traversal
    q = []
     
    # Enqueue Root and Initialize Height
    q.append(root)
    height = 0
 
    while(True):
         
        # nodeCount(queue size) indicates number of nodes
        # at current level
        nodeCount = len(q)
        if nodeCount == 0 :
            return height
     
        height += 1
 
        # Dequeue all nodes of current level and Enqueue
        # all nodes of next level
        while(nodeCount > 0):
            node = q[0]
            q.pop(0)
            if node.left is not None:
                q.append(node.left)
            if node.right is not None:
                q.append(node.right)
 
            nodeCount -= 1
 
 
# Driver program to test above function
# Let us create binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
 
print ("Height of tree is", treeHeight(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: linear
# Python 3 program to find
# height of complete binary
# tree from total nodes.
import math
def height(N):
    return math.ceil(math.log2(N + 1)) - 1
 
# driver node
N = 6
print(height(N))
 
# This code is contributed by
# Smitha Dinesh Semwal

Time complexity: constant
Space complexity: constant
# Program to find height of the tree considering
# only even level leaves.
 
# Helper class that allocates a new node with the
# given data and None left and right pointers.
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
def heightOfTreeUtil(root, isEven):
     
    # Base Case
    if (not root):
        return 0
 
    if (not root.left and not root.right):
        if (isEven):
            return 1
        else:
            return 0
 
    # left stores the result of left subtree,
    # and right stores the result of right subtree
    left = heightOfTreeUtil(root.left, not isEven)
    right = heightOfTreeUtil(root.right, not isEven)
 
    #If both left and right returns 0, it means
    # there is no valid path till leaf node
    if (left == 0 and right == 0):
        return 0
 
    return (1 + max(left, right))
 
def heightOfTree(root):
    return heightOfTreeUtil(root, False)
 
# Driver Code
if __name__ == '__main__':
     
    # Let us create binary tree shown
    # in above diagram
    root = newNode(1)
 
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
    root.left.right.left = newNode(6)
    print("Height of tree is",
           heightOfTree(root))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 program to find the diameter of binary tree
 
# A binary tree node
 
 
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
 
# The function Compute the "height" of a tree. Height is the
# number of nodes along the longest path from the root node
# down to the farthest leaf node.
 
def height(node):
 
    # Base Case : Tree is empty
    if node is None:
        return 0
 
    # If tree is not empty then height = 1 + max of left
    # height and right heights
    return 1 + max(height(node.left), height(node.right))
 
# Function to get the diameter of a binary tree
 
 
def diameter(root):
 
    # Base Case when tree is empty
    if root is None:
        return 0
 
    # Get the height of left and right sub-trees
    lheight = height(root.left)
    rheight = height(root.right)
 
    # Get the diameter of left and right sub-trees
    ldiameter = diameter(root.left)
    rdiameter = diameter(root.right)
 
    # Return max of the following tree:
    # 1) Diameter of left subtree
    # 2) Diameter of right subtree
    # 3) Height of left subtree + height of right subtree +1
    return max(lheight + rheight + 1, max(ldiameter, rdiameter))
 
 
# Driver Code
if __name__ == "__main__":
    """
    Constructed binary tree is
                1
              /   \
            2      3
          /  \
        4     5
    """
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
 
    # Function Call
    print(diameter(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: quadratic
Space complexity: linear
# Python3 program to find the diameter of a binary tree
# A binary tree Node
 
 
class Node:
 
    # Constructor to create a new Node
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# utility class to pass height object
 
 
class Height:
    def __init(self):
        self.h = 0
 
# Optimised recursive function to find diameter
# of binary tree
 
 
def diameterOpt(root, height):
 
    # to store height of left and right subtree
    lh = Height()
    rh = Height()
 
    # base condition- when binary tree is empty
    if root is None:
        height.h = 0
        return 0
 
    # ldiameter --> diameter of left subtree
    # rdiameter  --> diameter of right subtree
 
    # height of left subtree and right subtree is obtained from lh and rh
    # and returned value of function is stored in ldiameter and rdiameter
 
    ldiameter = diameterOpt(root.left, lh)
    rdiameter = diameterOpt(root.right, rh)
 
    # height of tree will be max of left subtree
    # height and right subtree height plus1
 
    height.h = max(lh.h, rh.h) + 1
 
    # return maximum of the following
    # 1)left diameter
    # 2)right diameter
    # 3)left height + right height + 1
    return max(lh.h + rh.h + 1, max(ldiameter, rdiameter))
 
# function to calculate diameter of binary tree
 
 
def diameter(root):
    height = Height()
    return diameterOpt(root, height)
 
 
# Driver Code
if __name__ == "__main__":
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
 
    """
  Constructed binary tree is
              1
          /   \
          2      3
        /  \
      4     5
  """
 
    print("The diameter of the binary tree is:", end=" ")
    # Function Call
    print(diameter(root))
 
# This code is contributed by Shweta Singh(shweta44)

Time complexity: linear
Space complexity: linear
# Simple Python3 program to find diameter
# of a binary tree.
 
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Function to find height of a tree
def height(root, ans):
    if (root == None):
        return 0
 
    left_height = height(root.left, ans)
 
    right_height = height(root.right, ans)
 
    # update the answer, because diameter
    # of a tree is nothing but maximum
    # value of (left_height + right_height + 1)
    # for each node
    ans[0] = max(ans[0], 1 + left_height +
                             right_height)
 
    return 1 + max(left_height,
                   right_height)
 
# Computes the diameter of binary
# tree with given root.
def diameter(root):
    if (root == None):
        return 0
    ans = [-999999999999] # This will store
                          # the final answer
    height_of_tree = height(root, ans)
    return ans[0]
 
# Driver code
if __name__ == '__main__':
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
 
    print("Diameter is", diameter(root))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: logn
# Python3 program to find closest
# value in Binary search Tree
 
_MIN = -2147483648
_MAX = 2147483648
 
# Helper function that allocates a new
# node with the given data and None 
# left and right pointers.                                    
class newnode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# utility function to return level
# of given node
def getDeepestRightLeafNode(root) :
 
    if (not root):
        return None
 
    # create a queue for level
    # order traversal
    q = []
    q.append(root)
 
    result = None
 
    # traverse until the queue is empty
    while (len(q)):
        temp = q[0]
        q.pop(0)
 
        if (temp.left):
            q.append(temp.left)
         
        # Since we go level by level, the last
        # stored right leaf node is deepest one
        if (temp.right):
            q.append(temp.right)
            if (not temp.right.left and
                not temp.right.right):
                result = temp.right
 
    return result
 
# Driver Code
if __name__ == '__main__':
     
    # create a binary tree
    root = newnode(1)
    root.left = newnode(2)
    root.right = newnode(3)
    root.left.right = newnode(4)
    root.right.left = newnode(5)
    root.right.right = newnode(6)
    root.right.left.right = newnode(7)
    root.right.right.right = newnode(8)
    root.right.left.right.left = newnode(9)
    root.right.right.right.right = newnode(10)
 
    result = getDeepestRightLeafNode(root)
    if result:
        print("Deepest Right Leaf Node ::",
                               result.data)
    else:
        print("No result, right leaf not found")
         
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: linear
Space complexity: linear
"""Python3 program to find value of the
deepest node in a given binary tree"""
 
# A Binary Tree Node
# Utility function to create a
# new tree node
class newNode:
 
    # Constructor to create a newNode
    def __init__(self, data):
        self.data= data
        self.left = None
        self.right = None
        self.visited = False
 
# maxLevel : keeps track of maximum
# level seen so far.
# res : Value of deepest node so far.
# level : Level of root
def find(root, level, maxLevel, res):
 
    if (root != None):
        level += 1
        find(root.left, level, maxLevel, res)
 
        # Update level and rescue
        if (level > maxLevel[0]):
         
            res[0] = root.data
            maxLevel[0] = level
         
        find(root.right, level, maxLevel, res)
         
# Returns value of deepest node
def deepestNode(root) :
 
    # Initialize result and max level
    res = [-1]
    maxLevel = [-1]
 
    # Updates value "res" and "maxLevel"
    # Note that res and maxLen are passed
    # by reference.
    find(root, 0, maxLevel, res)
    return res[0]
                         
# Driver Code
if __name__ == '__main__':
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.right.left = newNode(5)
    root.right.right = newNode(6)
    root.right.left.right = newNode(7)
    root.right.right.right = newNode(8)
    root.right.left.right.left = newNode(9)
    print(deepestNode(root))
 
# This code is contributed by
# SHUBHAMSINGH10

Time complexity: linear
Space complexity: linear
# A Python3 program to find value of the
# deepest node in a given binary tree by method 3
from collections import deque
 
class new_Node:
    def __init__(self, key):
        self.data = key
        self.left = self.right = None
 
def deepestNode(root):
    if root == None:
        return 0
    q = deque()
    q.append(root)
    node = None
    while len(q) != 0:
        node = q.popleft()
        if node.left is not None:
            q.append(node.left)
        if node.right is not None:
            q.append(node.right)
    return node.data
  
# Driver Code
if __name__ == '__main__':
  
    root = new_Node(1)
    root.left = new_Node(2)
    root.right = new_Node(3)
    root.left.left = new_Node(4)
    root.right.left = new_Node(5)
    root.right.right = new_Node(6)
    root.right.left.right = new_Node(7)
    root.right.right.right = new_Node(8)
    root.right.left.right.left = new_Node(9)
      
    # Calculating height of tree
    levels = deepestNode(root)
      
    # Printing the deepest node
    print(levels)
     
# This code is contributed by Aprajita Chhawi

Time complexity: linear
Space complexity: linear
# Python3 program to find deepest
# left leaf Binary search Tree
 
_MIN = -2147483648
_MAX = 2147483648
 
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.                                    
class newnode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# utility function to return deepest
# left leaf node
def getDeepestLeftLeafNode(root) :
 
    if (not root):
        return None
 
    # create a queue for level
    # order traversal
    q = []
    q.append(root)
 
    result = None
 
    # traverse until the queue is empty
    while (len(q)):
        temp = q[0]
        q.pop(0)
 
        if (temp.left):
            q.append(temp.left)
            if (not temp.left.left and
                not temp.left.right):
                result = temp.left
         
        # Since we go level by level,
        # the last stored right leaf
        # node is deepest one
        if (temp.right):
            q.append(temp.right)        
     
    return result
 
# Driver Code
if __name__ == '__main__':
     
    # create a binary tree
    root = newnode(1)
    root.left = newnode(2)
    root.right = newnode(3)
    root.left.Left = newnode(4)
    root.right.left = newnode(5)
    root.right.right = newnode(6)
    root.right.left.right = newnode(7)
    root.right.right.right = newnode(8)
    root.right.left.right.left = newnode(9)
    root.right.right.right.right = newnode(10)
 
    result = getDeepestLeftLeafNode(root)
    if result:
        print("Deepest Left Leaf Node ::",
                              result.data)
    else:
        print("No result, Left leaf not found")
         
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: linear
Space complexity: linear
# Python program to find the maximum width of
# binary tree using Level Order Traversal.
 
# A binary tree node
 
 
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to get the maximum width of a binary tree
 
 
def getMaxWidth(root):
    maxWidth = 0
    h = height(root)
    # Get width of each level and compare the
    # width with maximum width so far
    for i in range(1, h+1):
        width = getWidth(root, i)
        if (width > maxWidth):
            maxWidth = width
    return maxWidth
 
# Get width of a given level
 
 
def getWidth(root, level):
    if root is None:
        return 0
    if level == 1:
        return 1
    elif level > 1:
        return (getWidth(root.left, level-1) +
                getWidth(root.right, level-1))
 
# UTILITY FUNCTIONS
# Compute the "height" of a tree -- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node.
 
 
def height(node):
    if node is None:
        return 0
    else:
 
        # compute the height of each subtree
        lHeight = height(node.left)
        rHeight = height(node.right)
 
        # use the larger one
        return (lHeight+1) if (lHeight > rHeight) else (rHeight+1)
 
 
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
 
"""
Constructed binary tree is:
    1
    / \
    2 3
    / \     \
4 5 8
        / \
        6 7
"""
# Function call
print ("Maximum width is %d" % (getMaxWidth(root)))
 
# This code is contributed by Naveen Aili

Time complexity: quadratic
Space complexity: constant
# Python program to find the maximum width of binary
# tree using Level Order Traversal with queue.
 
from _collections import deque
 
# A binary tree node
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to get the maximum width of a binary tree
 
 
def getMaxWidth(root):
    # base case
    if root is None:
        return 0
    q = deque()
    maxWidth = 0
 
    q.append(root)
 
    while q:
        # Get the size of queue when the level order
        # traversal for one level finishes
        count = len(q)
 
        # Update the maximum node count value
        maxWidth = max(count, maxWidth)
 
        while (count is not 0):
            count = count-1
            temp = q.popleft()
            if temp.left is not None:
                q.append(temp.left)
 
            if temp.right is not None:
                q.append(temp.right)
 
    return maxWidth
 
 
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
 
"""
Constructed binary tree is:
       1
      / \
     2   3
    / \    \
   4   5   8
          / \
         6   7
"""
# Function call
print ("Maximum width is %d" % (getMaxWidth(root)))
 
# This code is contributed by Naveen Aili

Time complexity: linear
Space complexity: constant
# Python program to find the maximum width of
# binary tree using Preorder Traversal.
 
# A binary tree node
 
 
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to get the maximum width of a binary tree
 
 
def getMaxWidth(root):
    h = height(root)
    # Create an array that will store count of nodes at each level
    count = [0] * h
 
    level = 0
    # Fill the count array using preorder traversal
    getMaxWidthRecur(root, count, level)
 
    # Return the maximum value from count array
    return getMax(count, h)
 
# A function that fills count array with count of nodes at every
# level of given binary tree
 
 
def getMaxWidthRecur(root, count, level):
    if root is not None:
        count[level] += 1
        getMaxWidthRecur(root.left, count, level+1)
        getMaxWidthRecur(root.right, count, level+1)
 
# UTILITY FUNCTIONS
# Compute the "height" of a tree -- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node.
 
 
def height(node):
    if node is None:
        return 0
    else:
        # compute the height of each subtree
        lHeight = height(node.left)
        rHeight = height(node.right)
        # use the larger one
        return (lHeight+1) if (lHeight > rHeight) else (rHeight+1)
 
# Return the maximum value from count array
 
 
def getMax(count, n):
    max = count[0]
    for i in range(1, n):
        if (count[i] > max):
            max = count[i]
    return max
 
 
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
 
"""
Constructed binary tree is:
       1
      / \
     2   3
    / \   \
   4   5   8
          / \
         6   7
"""
 
print ("Maximum width is %d" % (getMaxWidth(root)))
 
# This code is contributed by Naveen Aili

Time complexity: linear
Space complexity: logn
# Python code to find vertical
# width of a binary tree
 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Function to fill hd in set.
def fillSet(root, s, hd):
    if (not root):
        return
 
    fillSet(root.left, s, hd - 1)
    s.add(hd)
    fillSet(root.right, s, hd + 1)
 
def verticalWidth(root):
    s = set()
 
    # Third parameter is horizontal
    # distance
    fillSet(root, s, 0)
 
    return len(s)
 
if __name__ == '__main__':
 
    # Creating the above tree
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)
    root.right.left.right = Node(8)
    root.right.right.right = Node(9)
 
    print(verticalWidth(root))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python program to determine whether
# vertical level l of binary tree
# is sorted or not.
from collections import deque
from sys import maxsize
 
INT_MIN = -maxsize
 
# Structure of a tree node.
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Helper function to determine if
# vertical level l of given binary
# tree is sorted or not.
def isSorted(root: Node, level: int) -> bool:
 
    # If root is null, then the answer is an
    # empty subset and an empty subset is
    # always considered to be sorted.
    if root is None:
        return True
 
    # Variable to store previous
    # value in vertical level l.
    prevVal = INT_MIN
 
    # Variable to store current level
    # while traversing tree vertically.
    currLevel = 0
 
    # Variable to store current node
    # while traversing tree vertically.
    currNode = Node(0)
 
    # Declare queue to do vertical order
    # traversal. A pair is used as element
    # of queue. The first element in pair
    # represents the node and the second
    # element represents vertical level
    # of that node.
    q = deque()
 
    # Insert root in queue. Vertical level
    # of root is 0.
    q.append((root, 0))
 
    # Do vertical order traversal until
    # all the nodes are not visited.
    while q:
        currNode = q[0][0]
        currLevel = q[0][1]
        q.popleft()
 
        # Check if level of node extracted from
        # queue is required level or not. If it
        # is the required level then check if
        # previous value in that level is less
        # than or equal to value of node.
        if currLevel == level:
            if prevVal <= currNode.key:
                prevVal = currNode.key
            else:
                return False
 
        # If left child is not NULL then push it
        # in queue with level reduced by 1.
        if currNode.left:
            q.append((currNode.left, currLevel - 1))
 
        # If right child is not NULL then push it
        # in queue with level increased by 1.
        if currNode.right:
            q.append((currNode.right, currLevel + 1))
 
    # If the level asked is not present in the
    # given binary tree, that means that level
    # will contain an empty subset. Therefore answer
    # will be true.
    return True
 
# Driver Code
if __name__ == "__main__":
 
    # /*
    #         1
    #         / \
    #     2 5
    #     / \
    #     7 4
    #         /
    #     6
    # */
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(5)
    root.left.left = Node(7)
    root.left.right = Node(4)
    root.left.right.left = Node(6)
 
    level = -1
    if isSorted(root, level):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: linear