199. 二叉树的右视图
xxxixxxx

199. 二叉树的右视图

解法一 BFS 广度优先 层序遍历

  • 时间复杂度
    O(n) 每个节点访问一次
  • 空间复杂度
    O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func rightSideView(_ root: TreeNode?) -> [Int] {
guard let root = root else { return [] }
var ans: [Int] = []
var treeList = [root]

while !treeList.isEmpty {
let count = treeList.count
for i in 0 ..< count {
let tree = treeList.remove(at: 0)
if i == count - 1 {
ans.append(tree.val)
}
if tree.left != nil {
treeList.append(tree.left!)
}
if tree.right != nil {
treeList.append(tree.right!)
}
}
}

return ans
}

解法二 DFS 深度优先 前序遍历 变形

  • 时间复杂度
    O(n) 每个节点访问一次
  • 空间复杂度
    O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var ans: [Int] = []
func rightSideView(_ root: TreeNode?) -> [Int] {
dfsSlideView(root, 0)
return ans
}

func dfsSlideView(_ root: TreeNode?, _ depth: Int) {
guard let root = root else { return }
if depth == ans.count {
ans.append(root.val)
}
let d = depth + 1
dfsSlideView(root.right, d)
dfsSlideView(root.left, d)
}
  • Post title:199. 二叉树的右视图
  • Post author:xxxixxxx
  • Create time:2021-02-24 23:22:00
  • Post link:https://xxxixxx.github.io/2021/02/24/2000-021-199. 二叉树的右视图/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments