<span>leetcode-1261 Find Elements in a Contaminated Binary Tree</span>

Given a binary tree with the following rules:

root.val == 0
If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2
Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.

You need to first recover the binary tree and then implement the FindElements class:

FindElements(TreeNode* root) Initializes the object with a contamined binary tree, you need to recover it first.
bool find(int target) Return if the target value exists in the recovered binary tree.

输入输出实例:

Input
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
Output
[null,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1]); 
findElements.find(1); // return False 
findElements.find(2); // return True 

本题思路其实很简单,就是还原树,然后再进行查找就行了,注意查找时及时停止,不然容易超时!

# 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 recover(self, root):
        if root != None:
            if root.left != None:
                root.left.val = 2 * root.val + 1
                self.recover(root.left)
            if root.right != None:
                root.right.val = 2 * root.val + 2
                self.recover(root.right)
        return root
    def __init__(self, root: TreeNode):
        root.val = 0
        self.root = self.recover(root)
        
    def check(self, root1, target):
        if root1 != None:
            if root1.val > target:
                return False
            if root1.val == target:
                return True
            else:
                return self.check(root1.left, target) or self.check(root1.right, target)
        return False
    
    def find(self, target: int) -> bool:
        return self.check(self.root, target)
        


# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)

 

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务