Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 199 · BFS / Level Order

Binary Tree Right Side View

LeetCode 199 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Right-first DFS; record the first node per level.

मध्यमTreeDepth-First SearchBreadth-First SearchBinary Tree

मी Binary Tree Right Side View (LeetCode 199) असा सोडवला — BFS / Level Order पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Do a DFS that visits the right child before the left. The first node you reach at each depth is the one visible from the right.

Approach

  1. 1

    dfs(node, level): None → return.

  2. 2

    If this level has no entry yet, record node.val.

  3. 3

    Recurse right, then left, with level + 1.

मी कसा सोडवला

Right-first DFSPythonO(n) time · O(h) space
class Solution:
    def rightSideView(self, root):
        ds = []

        def dfs(node, level):
            if node is None:
                return
            if len(ds) == level:
                ds.append(node.val)
            dfs(node.right, level + 1)
            dfs(node.left, level + 1)
        dfs(root, 0)
        return ds
स्टेप-थ्रू लोड होत आहे…

Binary Tree Right Side View — वारंवार विचारले जाणारे प्रश्न

Binary Tree Right Side View मागील intuition काय आहे?

Do a DFS that visits the right child before the left. The first node you reach at each depth is the one visible from the right.

Binary Tree Right Side View (LeetCode 199) कसा सोडवावा?

1. dfs(node, level): None → return. 2. If this level has no entry yet, record node.val. 3. Recurse right, then left, with level + 1.

Binary Tree Right Side View ची time आणि space complexity किती आहे?

Time: O(n). Space: O(h). (Accepted approach: Right-first DFS.)

Binary Tree Right Side View मध्ये सामान्य चुका कोणत्या?

A left-only branch deeper than the right side is still visible.