leetcode 1261. Find Elements in a Contaminated Binary Tree(python)

語言: CN / TW / HK

本文已參與「掘力星計劃」,贏取創作大禮包,挑戰創作激勵金。

描述

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.

Implement the FindElements class:

  • FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.
  • bool find(int target) Returns true if the target value exists in the recovered binary tree.

Example 1:

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

Example 2:

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

Example 3:

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

Note:

TreeNode.val == -1
The height of the binary tree is less than or equal to 20
The total number of nodes is between [1, 10^4]
Total calls of find() is between [1, 10^4]
0 <= target <= 10^6

解析

根據題意,給出了一棵樹,但是其中只能看到樹的結構,因為樹被汙染所有節點的值都是 -1 ,但是節點的值可以復現恢復,那就是根節點為 0 ,左節點的值是其父節點的值的兩倍加一,右節點的值是其父節點的值的兩倍加二。題目要求我們使用 __init__ 函式先恢復這顆樹,然後使用 find 函式判斷 target 是否存在於樹中。

思路比較簡單,就是用遞迴直接將樹的節點的值都計算出來存在一個列表當中,然後判斷 target 是否在列表中即可。其實這道題看起來複雜,實際上蠻簡單的。

解答

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class FindElements(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.vals = []
        def dfs(root, val):
            if not root:
                return
            self.vals.append(val)
            if root.left:
                dfs(root.left, val*2+1)
            if root.right:
                dfs(root.right, val*2+2)
        dfs(root, 0)


    def find(self, target):
        """
        :type target: int
        :rtype: bool
        """
        if target in self.vals:
            return True
        return False

執行結果

Runtime: 622 ms, faster than 6.67% of Python online submissions for Find Elements in a Contaminated Binary Tree.
Memory Usage: 19.2 MB, less than 76.67% of Python online submissions for Find Elements in a Contaminated Binary Tree.

解析

也可以使用佇列來解答這個題,構建樹的過程和上面過程類似,不再贅述。

解答

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class FindElements(object):
    def __init__(self, root):
        self.A = set()
        queue = collections.deque([[root,0]])
        while queue:
            n,x = queue.popleft()
            self.A.add(x)
            if n.left:
                queue.append( [n.left  , 2*x+1] )
            if n.right:
                queue.append( [n.right , 2*x+2] )

    def find(self, target):
        return target in self.A

執行結果

Runtime: 143 ms, faster than 33.33% of Python online submissions for Find Elements in a Contaminated Binary Tree.
Memory Usage: 19.7 MB, less than 13.33% of Python online submissions for Find Elements in a Contaminated Binary Tree.

原題連結:http://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/

您的支援是我最大的動力