码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-25 23:04:23      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:new   val   target   turn   pac   algorithm   tar   main   cstring   

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

LeetCode-1261

/**
 * 给出一个满足下述规则的二叉树:
 * root.val == 0
 * 如果 treeNode.val == x 且?treeNode.left != null,那么?treeNode.left.val == 2 * x + 1
 * 如果 treeNode.val == x 且 treeNode.right != null,那么?treeNode.right.val == 2 * x + 2
 * 现在这个二叉树受到「污染」,所有的?treeNode.val?都变成了?-1。
 * 请你先还原二叉树,然后实现?FindElements?类:
 * FindElements(TreeNode* root)?用受污染的二叉树初始化对象,你需要先把它还原。
 * bool find(int target)?判断目标值?target?是否存在于还原后的二叉树中并返回结果。
 **/
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
#include<map>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
       0
     /       1     2
   /   3  4
**/
class FindElements {
private:
    map<int,int>ma;
    void DFS(TreeNode* root){
        if(root->left){
            root->left->val=2*(root->val)+1;
            ma[root->left->val]++;
            DFS(root->left);
        }
        if(root->right){
            root->right->val=2*(root->val)+2;
            ma[root->right->val]++;
            DFS(root->right);
        }
    }
public:
    FindElements(TreeNode* root) {
        root->val=0;
        ma[0]++;
        DFS(root);
        
    }
    bool find(int target) {
        return ma[target];
    }
    
};
int main(){
    TreeNode* t1=new TreeNode(-1);
    TreeNode* t2=new TreeNode(-1);
    TreeNode* t3=new TreeNode(-1);
    TreeNode* t4=new TreeNode(-1);
    TreeNode* t5=new TreeNode(-1);
    t2->left=t4;t2->right=t5;
    t1->left=t2;t1->right=t3;
    FindElements* obj = new FindElements(t1);
    cout<<obj->find(3)<<endl;
    
    system("pause");
    return 0;
}

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

标签:new   val   target   turn   pac   algorithm   tar   main   cstring   

原文地址:https://www.cnblogs.com/GarrettWale/p/12364303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!