Tree DFS Flashcards

(5 cards)

1
Q

What is the pattern and when is Tree DFS used?

A

Explores tree depth-first via recursion or stack.

Use Case: Path finding, pre/post/inorder traversal.

Example: [Binary Tree Inorder Traversal]. Action: Verbalize use case aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps in Tree DFS?

A
  1. Process node (preorder) or recurse left/right.
  2. Recurse left, process (inorder), recurse right.
  3. Process after recursion (postorder).

Action: Explain steps for [Binary Tree Inorder Traversal] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does Tree DFS apply to [Binary Tree Inorder Traversal]?

A

Return inorder traversal of binary tree.
Approach: Recurse left, process node, recurse right.

Example: [Binary Tree Inorder Traversal]. Action: Verbalize solution logic aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas of Tree DFS?

A

Time: O(n), Space: O(h), h=height.

Gotchas: Empty tree, unbalanced tree.

Action: List edge cases for [Binary Tree Inorder Traversal] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Code example for Tree DFS.

A

```python
from typing import Optional, List
class TreeNode:
def __init__(self, val: int = 0, left: ‘TreeNode’ = None, right: ‘TreeNode’ = None) -> None:
self.val = val
self.left = left
self.right = right
def inorder_traversal(root: Optional[TreeNode]) -> List[int]:
result: List[int] = []
def dfs(node: Optional[TreeNode]) -> None:
if not node:
return
dfs(node.left)
result.append(node.val)
dfs(node.right)
dfs(root)
return result
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly