Binary Tree Inorder Traversal
LeetCode 94 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Left → node → right.
నేను Binary Tree Inorder Traversal (LeetCode 94) ను ఇలా పరిష్కరించాను — Traversals (Recursive / Iterative) ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
In-order means left subtree, then the node, then the right subtree. A recursive helper that follows that order appends values in sorted order for a BST.
Approach
- 1
dfs(None) returns.
- 2
dfs(left), record node.val, dfs(right).
నేను ఎలా పరిష్కరించాను
Recursive DFSPythonO(n) time · O(h) space
# 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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
#left,root,right
res = []
def dfs(node):
if node==None:
return None
dfs(node.left)
res.append(node.val)
dfs(node.right)
dfs(root)
return resBinary Tree Inorder Traversal — తరచూ అడిగే ప్రశ్నలు
Binary Tree Inorder Traversal వెనుక ఉన్న intuition ఏమిటి?
In-order means left subtree, then the node, then the right subtree. A recursive helper that follows that order appends values in sorted order for a BST.
Binary Tree Inorder Traversal (LeetCode 94) ను ఎలా పరిష్కరించాలి?
1. dfs(None) returns. 2. dfs(left), record node.val, dfs(right).
Binary Tree Inorder Traversal యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(h). (Accepted approach: Recursive DFS.)
Binary Tree Inorder Traversal లో సాధారణ పొరపాట్లు ఏమిటి?
An explicit stack avoids recursion limits on very deep trees.