qiaoxu123
1/3/2019 - 12:45 AM

965. Univalued Binary Tree

很简单一道题目,自己写的虽然陋不过也实现了,后面根据discuss完善一下。

  • 算法1:递归判断即可

  • 算法2:使用set数组的特性,最后判断set数组的大小即可

//Runtime: 4 ms, faster than 91.80%

class Solution {
public:
    int temp;
    bool flag = true;
    
    bool isUnivalTree(TreeNode* root) {
        if(!root) return NULL;
        temp = root->val;
        travelTree(root);
        return flag; 
    }
    
    void travelTree(TreeNode* root){
        if(root){
            travelTree(root->left);
            travelTree(root->right);
        
            if(flag)
                flag = root->val == temp ? true : false;
        }
    }
};
//Runtime: 4 ms, faster than 91.80%

class Solution {
public:
    set<int> array; 
    
    bool isUnivalTree(TreeNode* root) {
        travelTree(root);
        return array.size() > 1 ? false : true;
    }
    
    void travelTree(TreeNode* root){
        if(root){
            travelTree(root->left);
            travelTree(root->right);
            array.insert(root->val);  
        } 
    }
};