Binary Trees Flashcards
- Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
- Create base case, which is when it hits a leaf node, where root node is None and make that return 0
- Return 1 plus the max of the function call on the left and right node
Basically leaf node will return 1 + max(0,0) and will make its way up the stack/recursion
- Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
- Base case where both p and q are null, they are equal, so return True
- Case where p or q is null, they are not equal so return False
- Case where p.val and q.val is not equal, they are not equal so return False
- Last case, is calling on child nodes. So call isSameTree on both the left and right nodes and compare their bool value with “and”
- if True and True, True
- If True and False, False
- If False and False, False
- Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
- Check case where root is none. if so, just return null root
- create variables left and right, where they traverse down the left and right trees respectively using recursion
- swap the left and right by setting the root.left to right and root.right to left variables.
- return the root
- Construct Binary Tree from Preorder and Inorder Traversal
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
- Subtree of Another Tree
https://leetcode.com/problems/subtree-of-another-tree/
- Binary Tree Level Order Traversal
https://leetcode.com/problems/binary-tree-level-order-traversal/
- Validate Binary Search Tree
https://leetcode.com/problems/validate-binary-search-tree/
- Kth Smallest Element in a BST
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
- Lowest Common Ancestor of a Binary Search Tree
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
- Design Add and Search Words Data Structure
https://leetcode.com/problems/design-add-and-search-words-data-structure/
- Implement Trie (Prefix Tree)
https://leetcode.com/problems/implement-trie-prefix-tree/