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
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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.