解題思路
採用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