快轉到主要內容
  1. Posts/

Leetcode 1261. 從受污染的二元樹中找出元素

·1 分鐘
Data Structure and Algorithms LeetCode Solutions Leetcode-Solutions Dfs
目錄

這是 Leetcode 2025 年 2 月 21 日的每日一題。

題目描述
#

給定一棵二元樹,其原始規則如下:

  1. root.val == 0
  2. 對於任意 treeNode
    1. treeNode.valxtreeNode.left != null,則 treeNode.left.val == 2 * x + 1
    2. treeNode.valxtreeNode.right != null,則 treeNode.right.val == 2 * x + 2

現在這棵樹已被污染,也就是所有節點的值都變成了 -1

請實作 FindElements 類別:

  • FindElements(TreeNode* root):使用一棵受污染的二元樹初始化物件並恢復原始數值。
  • bool find(int target):若目標值存在於已恢復的樹中,則回傳 true

解題直覺
#

  1. 我們遍歷整棵樹並依照題目描述的規則更新每個節點的值。
  2. 更新後,將所有出現過的值存進一個哈希表中,以便快速查詢目標是否存在。

Code
#

class FindElements {
    private:
        unordered_map<int, bool> exist;
        void dfs(TreeNode* root, int val){
            if(!root){
                return;
            }
            else{
                root->val = val;
                exist[val] = true;
            }
            dfs(root->left, 2 * val + 1);
            dfs(root->right, 2 * val + 2);
        }

    public:
        FindElements(TreeNode* root) {
            dfs(root, 0);
        }
        
        bool find(int target) {
            return exist[target];
        }
};

感謝閱讀!歡迎留言分享你的想法與回饋!

相關文章

Leetcode 1415. 長度為 n 的所有快樂字串中字典序第 k 小的字串
·2 分鐘
Data Structure and Algorithms LeetCode Solutions Leetcode-Solutions Backtracking Dfs Combinations
Leetcode 1980. 找出不在清單中的二進位字串
·1 分鐘
Data Structure and Algorithms LeetCode Solutions Leetcode-Solutions
Leetcode 1079. 拼字組合數量
·1 分鐘
LeetCode Solutions Leetcode-Solutions Backtracking Dfs Combinations Permutations