C++ Using Binary Tree Method


  • 0
    S

    class Solution {
    public:

    int majorityElement(vector<int>& nums) {
    if (nums.size()==1) return nums[0];
    TreeNode * root=new TreeNode(nums[0]);
    root->val=nums[0];
    int a=nums[0];
    int count=1;
    for (int i=1;i<nums.size();i++){
        TreeNode * n=new TreeNode(nums[i]);
        TreeNode * tempt=root;
        while (1){
            if (nums[i]<=tempt->val){
                if (nums[i]==a){
                    count++;
                    break;
                }
                if (nums[i]!=a){
                    count--;
                    if (count==0){
                        a=nums[i];
                        count=1;
                        break;
                    }
                }
                if (tempt->left==NULL){
                    tempt->left=n;
                    break;
                }
                tempt=tempt->left;
                break;
            }
            if (nums[i]>tempt->val){
                if (nums[i]==a){
                    count++;
                    break;
                }
                if (nums[i]!=a){
                    count--;
                    if (count==0){
                        a=nums[i];
                        count=1;
                        break;
                    } 
                }
                if (tempt->right==NULL){
                    tempt->right=n;
                    break;
                }
                tempt=tempt->right;
                break;
            }
        }
    }
    return a;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.