LeetCode 199. 二叉樹的右視圖 Binary Tree Right Side View Python3解法

解題思路

採用DFS(深度優先遍歷),遍歷過程中對深度進行標記;
其次,爲了得到右視圖,先遍歷節點的右子樹,再遍歷左子樹

Python代碼

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        res = []
        def dfs(root, depth):
            if not root:
                return
            if depth > len(res):
                res.append(root.val)
            dfs(root.right, depth+1)
            dfs(root.left, depth+1)
        dfs(root, 1)
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章