Skip to main content

🎄Trees Questions

226. Invert Binary Tree​

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# inorder tranversal then pop reverse

stack = [root]

while len(stack):
curr = stack.pop()
if not curr:
continue

if curr.left:
stack.append(curr.left)
if curr.right:
stack.append(curr.right)

curr.left, curr.right = curr.right, curr.left
return root

104. Maximum Depth of Binary Tree​

class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))