1261. 在受污染的二叉树中查找元素

在受污染的二叉树中查找元素

解法一: 哈希

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type FindElements struct {
set map[int]bool
}

func Constructor(root *TreeNode) FindElements {
set := map[int]bool{}
var dfs func(node *TreeNode, cur int)
dfs = func(node *TreeNode, cur int) {
if node == nil {
return
}
set[cur] = true
dfs(node.Left, (cur<<1)+1)
dfs(node.Right, (cur<<1)+2)
}
dfs(root, 0)
return FindElements{
set,
}
}

func (this *FindElements) Find(target int) bool {
return this.set[target]
}

/**
* Your FindElements object will be instantiated and called as such:
* obj := Constructor(root);
* param_1 := obj.Find(target);
*/
作者

wuhunyu

发布于

2024-03-12

更新于

2025-01-15

许可协议