1261. 在受污染的二叉树中查找元素
题目描述
解题思路
1、重建跟二叉树遍历思路一样
2、查找过程这里是直接存下载,在参考中还有更好的方案
代码实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: TreeNode):
self.vals = set()
self.build(root, 0)
def build(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return
root.val = val
self.vals.add(val)
self.build(root.left, 2 * val + 1)
self.build(root.right, 2 * val + 2)
# return root
def find(self, target: int) -> bool:
return True if target in self.vals else False
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)