Python

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan 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


Set pelajaran terkait

Commutative and Associative Properties

View Set

Chapter 2: The Political, Legal and Technological Environment

View Set

CCNA Introduction to Networks Chapter 4

View Set

The Muscular System of the dog or cat

View Set

Advance MS Quiz #1 - ch 49, 65, 48 with a hint of ATI

View Set

ECON 2105 Unit 2: (Chp 6-9) Measurement, Finance, and Economic Growth

View Set

General Biology I Lab - Lab Safety Post Lab Questions

View Set

BADMA379 Ethics and Ethical Reasoning

View Set

Domain 8: Software Development Security

View Set