Python

¡Supera tus tareas y exámenes ahora con 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


Conjuntos de estudio relacionados

Series 65, Unit 7: Financial Reporting

View Set

Life and Health - Chapter 7 Quiz - Federal Tax Considerations and Retirement Plans

View Set

Module 2.1 Chapter 5. Social Roles.

View Set

Aging and Its Effects on the CP System

View Set

Robert J Oppenheimer atom bomb trial questions

View Set

Effects of Changing the Dimensions of a Figure Assignment and Quiz

View Set

ch.10 Firewall Design and Management

View Set

Nurs 6015 Exam 2 Practice Questions

View Set