Banana-Leopard/TASTY huggingface dataset:
# Python program to find maximumpath sum between two leaves
# of a binary tree
 
INT_MIN = -2**32
 
# 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
 
# Utility function to find maximum sum between any
# two leaves. This function calculates two values:
# 1) Maximum path sum between two leaves which are stored
#    in res
# 2) The maximum root to leaf path sum which is returned
# If one side of root is empty, then it returns INT_MIN
 
 
def maxPathSumUtil(root, res):
 
    # Base Case
    if root is None:
        return 0
 
    # if root is leaf node we can return root.data
    if not root.left and not root.right:
        return root.data
 
    # Find maximumsum in left and right subtree. Also
    # find maximum root to leaf sums in left and right
    # subtrees ans store them in ls and rs
    ls = maxPathSumUtil(root.left, res)
    rs = maxPathSumUtil(root.right, res)
 
    # If both left and right children exist
    if root.left is not None and root.right is not None:
 
        # update result if needed
        res[0] = max(res[0], ls + rs + root.data)
 
        # Return maximum possible value for root being
        # on one side
        return max(ls, rs) + root.data
 
    # If any of the two children is empty, return
    # root sum for root being on one side
    if root.left is None:
        return rs + root.data
    else:
        return ls + root.data
 
# The main function which returns sum of the maximum
# sum path betwee ntwo leaves. THis function mainly
# uses maxPathSumUtil()
 
 
def maxPathSum(root):
    res = [INT_MIN]
    res1 = maxPathSumUtil(root, res)
    # we have to check if root.left is None or root.right is None
    # for ex:-   10
    #            /  \
    #         None  -5
    # this will return INT_MIN but answer is 5 which is res1
    if root.left and root.right:
        return res[0]
    return max(res[0], res1)
 
 
# Driver program to test above function
root = Node(-15)
root.left = Node(5)
root.right = Node(6)
root.left.left = Node(-8)
root.left.right = Node(1)
root.left.left.left = Node(2)
root.left.left.right = Node(6)
root.right.left = Node(3)
root.right.right = Node(9)
root.right.right.right = Node(0)
root.right.right.right.left = Node(4)
root.right.right.right.right = Node(-1)
root.right.right.right.right.left = Node(10)
 
print("Max pathSum of the given binary tree is", maxPathSum(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: linear
# Python3 program to print all paths
# with sum k
  
# utility function to print contents of
# a vector from index i to it's end
  
  
def printVector(v, i):
    for j in range(i, len(v)):
        print(v[j], end=" ")
    print()
  
  
# Binary Tree Node
""" utility that allocates a newNode 
with the given key """
  
  
class newNode:
  
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
  
# This function prints all paths
# that have sum k
  
  
def printKPathUtil(root, path, k):
  
    # empty node
    if (not root):
        return
  
    # add current node to the path
    path.append(root.data)
  
    # check if there's any k sum path
    # in the left sub-tree.
    printKPathUtil(root.left, path, k)
  
    # check if there's any k sum path
    # in the right sub-tree.
    printKPathUtil(root.right, path, k)
  
    # check if there's any k sum path that
    # terminates at this node
    # Traverse the entire path as
    # there can be negative elements too
    f = 0
    for j in range(len(path) - 1, -1, -1):
        f += path[j]
  
        # If path sum is k, print the path
        if (f == k):
            printVector(path, j)
  
    # Remove the current element
    # from the path
    path.pop(-1)
  
# A wrapper over printKPathUtil()
  
  
def printKPath(root, k):
  
    path = []
    printKPathUtil(root, path, k)
  
  
# Driver Code
if __name__ == '__main__':
  
    root = newNode(1)
    root.left = newNode(3)
    root.left.left = newNode(2)
    root.left.right = newNode(1)
    root.left.right.left = newNode(1)
    root.right = newNode(-1)
    root.right.left = newNode(4)
    root.right.left.left = newNode(1)
    root.right.left.right = newNode(2)
    root.right.right = newNode(5)
    root.right.right.right = newNode(2)
  
    k = 5
    printKPath(root, k)
  
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: linear
Space complexity: logn
# Python3 program to find if there is a
# subtree with given sum
 
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newnode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# function to check if there exist any
# subtree with given sum
# cur_sum -. sum of current subtree
#            from ptr as root
# sum_left -. sum of left subtree from
#             ptr as root
# sum_right -. sum of right subtree
#              from ptr as root
def sumSubtreeUtil(ptr,cur_sum,sum):
 
    # base condition
    if (ptr == None):
        cur_sum[0] = 0
        return False
 
    # Here first we go to left sub-tree,
    # then right subtree then first we
    # calculate sum of all nodes of subtree
    # having ptr as root and assign it as cur_sum
    # cur_sum = sum_left + sum_right + ptr.data
    # after that we check if cur_sum == sum
    sum_left, sum_right = [0], [0]
    x=sumSubtreeUtil(ptr.left, sum_left, sum)
    y=sumSubtreeUtil(ptr.right, sum_right, sum)
    cur_sum[0] = (sum_left[0] +
                  sum_right[0] + ptr.data)
    return ((x or y)or (cur_sum[0] == sum))
 
# Wrapper over sumSubtreeUtil()
def sumSubtree(root, sum):
 
    # Initialize sum of subtree with root
    cur_sum = [0]
 
    return sumSubtreeUtil(root, cur_sum, sum)
 
# Driver Code
if __name__ == '__main__':
 
    root = newnode(8)
    root.left = newnode(5)
    root.right = newnode(4)
    root.left.left = newnode(9)
    root.left.right = newnode(7)
    root.left.right.left = newnode(1)
    root.left.right.right = newnode(12)
    root.left.right.right.right = newnode(2)
    root.right.right = newnode(11)
    root.right.right.left = newnode(3)
    sum = 22
 
    if (sumSubtree(root, sum)) :
        print("Yes" )
    else:
        print("No")
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: linear
Space complexity: logn
# Python3 implementation to count subtrees
# that Sum up to a given value x
 
# class to get a new node
 
 
class getNode:
    def __init__(self, data):
 
        # put in the data
        self.data = data
        self.left = self.right = None
 
# function to count subtrees that
# Sum up to a given value x
 
 
def countSubtreesWithSumX(root, count, x):
 
    # if tree is empty
    if (not root):
        return 0
 
    # Sum of nodes in the left subtree
    ls = countSubtreesWithSumX(root.left,
                               count, x)
 
    # Sum of nodes in the right subtree
    rs = countSubtreesWithSumX(root.right,
                               count, x)
 
    # Sum of nodes in the subtree
    # rooted with 'root.data'
    Sum = ls + rs + root.data
 
    # if true
    if (Sum == x):
        count[0] += 1
 
    # return subtree's nodes Sum
    return Sum
 
# utility function to count subtrees
# that Sum up to a given value x
 
 
def countSubtreesWithSumXUtil(root, x):
 
    # if tree is empty
    if (not root):
        return 0
 
    count = [0]
 
    # Sum of nodes in the left subtree
    ls = countSubtreesWithSumX(root.left,
                               count, x)
 
    # Sum of nodes in the right subtree
    rs = countSubtreesWithSumX(root.right,
                               count, x)
 
    # if tree's nodes Sum == x
    if ((ls + rs + root.data) == x):
        count[0] += 1
 
    # required count of subtrees
    return count[0]
 
 
# Driver Code
if __name__ == '__main__':
 
    # binary tree creation
    #         5
    #         / \
    #     -10     3
    #     / \ / \
    #     9 8 -4 7
    root = getNode(5)
    root.left = getNode(-10)
    root.right = getNode(3)
    root.left.left = getNode(9)
    root.left.right = getNode(8)
    root.right.left = getNode(-4)
    root.right.right = getNode(7)
 
    x = 7
 
    print("Count =",
          countSubtreesWithSumXUtil(root, x))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: logn
# Python3 program to find if there is
# a subtree with given sum
 
# Structure of a node of binary tree
 
 
class Node:
 
    def __init__(self, data):
 
        self.data = data
        self.left = None
        self.right = None
 
# Function to get a new node
 
 
def getNode(data):
 
    # Allocate space
    newNode = Node(data)
    return newNode
 
 
count = 0
ptr = None
 
# Utility function to count subtrees that
# sum up to a given value x
 
 
def countSubtreesWithSumXUtil(root, x):
 
    global count, ptr
 
    l = 0
    r = 0
 
    if (root == None):
        return 0
 
    l += countSubtreesWithSumXUtil(root.left, x)
    r += countSubtreesWithSumXUtil(root.right, x)
 
    if (l + r + root.data == x):
        count += 1
 
    if (ptr != root):
        return l + root.data + r
 
    return count
 
 
# Driver code
if __name__ == '__main__':
 
    ''' binary tree creation
              5
            /  \
          -10   3
          / \  / \
          9 8 -4 7
    '''
 
    root = getNode(5)
    root.left = getNode(-10)
    root.right = getNode(3)
    root.left.left = getNode(9)
    root.left.right = getNode(8)
    root.right.left = getNode(-4)
    root.right.right = getNode(7)
 
    x = 7
    ptr = root
 
    print("Count = " + str(countSubtreesWithSumXUtil(
        root, x)))
 
# This code is contributed by pratham76

Time complexity: linear
Space complexity: logn
# Python3 Implementation to find the maximum Spiral Sum
 
# Structure of a node in binary tree
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
 
# function to find the maximum sum contiguous subarray
# implementing kadane's algorithm
def maxSum(Arr):
 
    currSum = maxSum = 0
    for element in Arr:
        currSum = max(currSum + element, element)
        maxSum = max(maxSum, currSum)
 
    return maxSum
 
# function to find maximum spiral sum
def maxSpiralSum(root):
 
    # if tree is empty
    if not root:
        return 0
 
    # create two stacks to stopre alternative levels
    stack_s1 = [] # from levels right to left
    stack_s2 = [] # from levels left to right
 
    # store spiral order traversal in Arr
    Arr = []
    stack_s1.append(root)
 
    # traversing tree in spiral form
    # until there are elements in any one
    # of the stack
    while stack_s1 or stack_s2:
 
        # traverse current level from s1 and
        # push node of next level to s2
        while stack_s1:
             
            temp = stack_s1.pop()
 
            # append temp-> data to Arr
            Arr.append(temp.data)
 
            if temp.right:
                stack_s2.append(temp.right)
            if temp.left:
                stack_s2.append(temp.left)
 
        # traverse current level from s2 and
        # push node of next level to s1
        while stack_s2:
             
            temp = stack_s2.pop()
 
            # append temp-> data to Arr
            Arr.append(temp.data)
 
            if temp.left:
                stack_s1.append(temp.left)
            if temp.right:
                stack_s1.append(temp.right)
 
    return maxSum(Arr)
 
# Driver code
if __name__ == "__main__":
 
    root = Node(-2)
    root.left = Node(-3)
    root.right = Node(4)
    root.left.left = Node(5)
    root.left.right = Node(1)
    root.right.left = Node(-2)
    root.right.right = Node(-1)
    root.left.left.left = Node(-3)
    root.right.right.right = Node(2)
 
    print("Maximum Spiral Sum is : ", maxSpiralSum(root))
 
# This code is contributed by
# Mayank Chaudhary (chaudhary_19)

Time complexity: linear
Space complexity: linear
# Python3 implementation to find the sum
# of leaf node at minimum level
from collections import deque
 
# Structure of a node in binary tree
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
 
# function to find the sum of leaf nodes
# at minimum level
def sumOfLeafNodesAtLeafLevel(root):
 
    # if tree is empty
    if not root:
        return 0
 
    # if there is only root node
    if not root.left and not root.right:
        return root.data
 
    # Queue used for level order traversal
    Queue = deque()
    sum = f = 0
 
    # push root node in the queue
    Queue.append(root)
 
    while not f:
         
        # count no. of nodes present at current level
        nc = len(Queue)
 
        # traverse current level nodes
        while nc:
            top = Queue.popleft()
 
            # if node is leaf node
            if not top.left and not top.right:
                sum += top.data
 
                # set flag = 1 to signify that
                # we have encountered the minimum level
                f = 1
            else:
 
                # if top's left or right child exist
                # push them to Queue
                if top.left:
                    Queue.append(top.left)
                if top.right:
                    Queue.append(top.right)
            nc -= 1
 
    # return the sum
    return sum
 
# Driver code
if __name__ == "__main__":
 
    # binary tree creation
    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.left.right.left = Node(8)
    root.right.left.right = Node(9)
 
    print("Sum = ", sumOfLeafNodesAtLeafLevel(root))
 
# This code is contributed by
# Mayank Chaudhary (chaudhary_19)

Time complexity: linear
Space complexity: linear
# Python3 implementation of above approach
 
 
# Structure of a node in binary tree
class Node:
 
    def __init__(self, data):
 
        self.data = data
        self.left = None
        self.right = None
 
 
mp = dict()
def solve(root,level):
    if(root == None):
        return
    if root.left == None and root.right == None :
        try:
            mp[level].append(root.data)
        except:
            mp[level] = [root.data]
    solve(root.left, level+1)
    solve(root.right, level+1)
 
def minLeafSum(root):
 
    solve(root, 0)
    sum = 0
    for x, i in enumerate(sorted(mp)):
        for j in mp[i]:
            sum += j
        return sum
 
 
 
# Driver code
if __name__ == "__main__":
 
    # binary tree creation
    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)
 
    print("Sum = ", minLeafSum(root))
 
# This code is contributed by
# Abhijeet Kumar(abhijeet19403)

Time complexity: linear
Space complexity: linear
# Python3 program to find if
# there is a root to sum path
 
# 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
 
 
"""
 Given a tree and a sum, return
 true if there is a path from the root
 down to a leaf, such that
 adding up all the values along the path
 equals the given sum.
  
 Strategy: subtract the node
 value from the sum when recurring down,
 and check to see if the sum
 is 0 when you run out of tree.
"""
# s is the sum
 
 
def hasPathSum(node, s):
    ans = 0
    subSum = s - node.data
 
    # If we reach a leaf node and sum becomes 0, then
    # return True
    if(subSum == 0 and node.left == None and node.right == None):
        return True
 
    # Otherwise check both subtrees
    if node.left is not None:
        ans = ans or hasPathSum(node.left, subSum)
    if node.right is not None:
        ans = ans or hasPathSum(node.right, subSum)
 
    return ans
 
# Driver's Code
if __name__ == "__main__":
    s = 21
    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)
    root.left.right = Node(5)
    root.left.left = Node(3)
    root.right.left = Node(2)
     
    # Function call
    if hasPathSum(root, s):
        print("There is a root-to-leaf path with sum %d" % (s))
    else:
        print("There is no root-to-leaf path with sum %d" % (s))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: logn
# Python program to find sum of all paths from root to leaves
 
# 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
 
# Returns sums of all root to leaf paths. The first parameter is root
# of current subtree, the second paramete"r is value of the number
# formed by nodes from root to this node
def treePathsSumUtil(root, val):
 
    # Base Case
    if root is None:
        return 0
 
    # Update val
    val = (val*10 + root.data)
 
    # If current node is leaf, return the current value of val
    if root.left is None and root.right is None:
        return val
 
    # Recur sum of values for left and right subtree
    return (treePathsSumUtil(root.left, val) +
            treePathsSumUtil(root.right, val))
 
# A wrapper function over treePathSumUtil()
def treePathsSum(root):
     
    # Pass the initial value as 0 as ther is nothing above root
    return treePathsSumUtil(root, 0)
 
# Driver function to test above function
root = Node(6)
root.left = Node(3)
root.right = Node(5)
root.left.left = Node(2)
root.left.right = Node(5)
root.right.right = Node(4)
root.left.right.left = Node(7)
root.left.right.right = Node(4)
print ("Sum of all paths is", treePathsSum(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: linear
# Python program to find sum of all paths from root to leaves
 
# 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
 
 
def treePathsSumUtil(root, currPath, allPath):
   
    # Base Case
    if root is None:
        return
 
    # append the root data in string format in currPath
    currPath.append(str(root.data))
 
    # if we found a leaf node we copy the currPath to allPath
    if root.left is None and root.right is None:
        allPath.append(currPath.copy())
 
    # traverse in the left subtree
    treePathsSumUtil(root.left, currPath, allPath)
 
    # traverse in the right subtree
    treePathsSumUtil(root.right, currPath, allPath)
 
    # remove the current element from the path
    del currPath[-1]
 
 
def treePathsSum(root):
    # store all the root to leaf path in allPath
    allPath = []
 
    treePathsSumUtil(root, [], allPath)
    # store the sum
    s = 0
 
    for pathNumber in allPath:
        # join the pathNumbers to convert them  into the number to calculate sum
        k = "".join(pathNumber)
        s += int(k)
    return s
 
 
# Driver function to test above function
root = Node(6)
root.left = Node(3)
root.right = Node(5)
root.left.left = Node(2)
root.left.right = Node(5)
root.right.right = Node(4)
root.left.right.left = Node(7)
root.left.right.right = Node(4)
print("Sum of all paths is", treePathsSum(root))
 
# this code is contributed by Vivek Maddeshiya

Time complexity: quadratic
Space complexity: linear
"""Find root of tree where children
sum for every node id is given"""
 
def findRoot(arr, n) :
 
    # Every node appears once as an id, and
    # every node except for the root appears
    # once in a sum. So if we subtract all
    # the sums from all the ids, we're left
    # with the root id.
    root = 0
    for i in range(n):
        root += (arr[i][0] - arr[i][1])
    return root
                         
# Driver Code
if __name__ == '__main__':
 
    arr = [[1, 5], [2, 0],
           [3, 0], [4, 0],
           [5, 5], [6, 5]]
    n = len(arr)
    print(findRoot(arr, n))
 
# This code is contributed
# by SHUBHAMSINGH10

Time complexity: linear
Space complexity: constant
# Python3 program to find maximum difference
# between node and its ancestor
 
_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, key):
        self.key = key
        self.left = None
        self.right = None
 
 
"""
Recursive function to calculate maximum
ancestor-node difference in binary tree.
It updates value at 'res' to store the
result. The returned value of this function
is minimum value in subtree rooted with 't' """
 
 
def maxDiffUtil(t, res):
    """ Returning Maximum value if node
    is not there (one child case) """
    if (t == None):
        return _MAX, res
 
    """ If leaf node then just return
        node's value """
    if (t.left == None and t.right == None):
        return t.key, res
 
    """ Recursively calling left and right
    subtree for minimum value """
    a, res = maxDiffUtil(t.left, res)
    b, res = maxDiffUtil(t.right, res)
    val = min(a, b)
 
    """ Updating res if (node value - minimum
    value from subtree) is bigger than res """
    res = max(res, t.key - val)
 
    """ Returning minimum value got so far """
    return min(val, t.key), res
 
 
""" This function mainly calls maxDiffUtil() """
 
 
def maxDiff(root):
 
    # Initialising result with minimum value
    res = _MIN
    x, res = maxDiffUtil(root, res)
    return res
 
 
""" Helper function to print inorder
traversal of binary tree """
 
 
def inorder(root):
 
    if (root):
 
        inorder(root.left)
        prf("%d ", root.key)
        inorder(root.right)
 
 
# Driver Code
if __name__ == '__main__':
 
    """
    Let us create Binary Tree shown
    in above example """
    root = newNode(8)
    root.left = newNode(3)
 
    root.left.left = newNode(1)
    root.left.right = newNode(6)
    root.left.right.left = newNode(4)
    root.left.right.right = newNode(7)
 
    root.right = newNode(10)
    root.right.right = newNode(14)
    root.right.right.left = newNode(13)
    print(maxDiff(root))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: linear
Space complexity: linear
# Python3 program to count 
# number of ways to color
# a N node skewed tree with
# k colors such that parent
# and children have different
# colors.
 
# fast_way is recursive
# method to calculate power
def fastPow(N, K):
    if (K == 0):
        return 1;
     
    temp = fastPow(N, int(K / 2));
    if (K % 2 == 0):
        return temp * temp;
    else:
        return N * temp * temp;
 
def countWays(N, K):
    return K * fastPow(K - 1, N - 1);
 
# Driver Code
N = 3;
K = 3;
print(countWays(N, K));
 
# This code is contributed by mits

Time complexity: logn
Space complexity: constant
# Python Program to calculate size of the tree iteratively
  
# Node Structure
class newNode:
    def __init__(self,data):
        self.data = data
        self.left = self.right = None
          
# Return size of tree
def sizeoftree(root):
    if root == None:
        return 0
    q = []
    q.append(root)
    count = 1
    while(len(q) != 0):
        root = q.pop(0)
        if(root.left):
            q.append(root.left)
            count += 1
        if(root.right):
            q.append(root.right)
            count += 1
    return count
      
# Driver Program
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
print(sizeoftree(root))
  
# This is code is contributed by simranjenny84

Time complexity: linear
Space complexity: np