Python

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

class Math: @staticmethod def add(x, y): return x + y @staticmethod def multiply(x, y): return x * y print(Math.add(2, 3)) # Output: 5 print(Math.multiply(4, 5)) # Output: 20

A static method in Python is a method that belongs to the class itself, rather than any specific instance of the class. It is defined using the @staticmethod decorator and can be called without creating an instance of the class.

Inorder

class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorder_traversal(root): if root: inorder_traversal(root.left) # Traverse the left subtree print(root.val, end=" ") # Visit the root inorder_traversal(root.right) # Traverse the right subtree # Example usage root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) print("Inorder Traversal:") inorder_traversal(root) # Output: 4 2 5 1 3

Post Order

class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def postorder_traversal(root): if root: postorder_traversal(root.left) # Traverse the left subtree postorder_traversal(root.right) # Traverse the right subtree print(root.val, end=" ") # Visit the root # Example usage root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) print("Postorder Traversal:") postorder_traversal(root) # Output: 4 5 2 3 1

Pre Order Tree Transversal

class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def preorder_traversal(root): if root: print(root.val, end=" ") # Visit the root preorder_traversal(root.left) # Traverse the left subtree preorder_traversal(root.right) # Traverse the right subtree # Example usage root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) print("Preorder Traversal:") preorder_traversal(root) # Output: 1 2 4 5 3


संबंधित स्टडी सेट्स

อิทอิส Chapter 2 Q:1-40

View Set

Finance in Sport and Rec Midterm

View Set

Adult 1 Exam 4 Ch. 24 Chronic Pulmonary Disease

View Set

RNSG 1343 Complex Concepts of Adult Health Ch 19 Evolve

View Set