222. Count Complete Tree Nodes

来源:互联网 发布:每天一杯速溶咖啡 知乎 编辑:程序博客网 时间:2024/05/22 15:10

答案正确但是超时,==,本以为采用对分的方法就可以了,,哭==,帖上对分的方式。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool judge(int num,int height,TreeNode* root)    {        stack<int> path;        for(int i=0;i<height+1;i++)        {            path.push(num);            num=num/2;        }        TreeNode* temp=root;        int top=path.top();        path.pop();        while((!path.empty())&&temp!=NULL)        {            if(path.top()-top*2==0)                temp=temp->left;            else                temp=temp->right;            top=path.top();            path.pop();        }        if(temp==NULL)            return false;        else            return true;    }    int countNodes(TreeNode* root) {        if(root==NULL)            return 0;        //get height        int height=0;        TreeNode* temp=root;        while(!(temp->left==NULL&&temp->right==NULL))        {            temp=temp->left;            height++;        }        int left=0;        int right=pow(2,height)-1;        while(right-left>1)        {            int mid=left+(right-left)/2;            if(judge(mid,height,root)==true)                left=mid;            else                right=mid-1;        }        //cout<<height;        if(judge(right,height,root)==true)            return right+1+pow(2,height)-1;        else if(judge(left,height,root)==true)            return left+1+pow(2,height)-1;        else{}        return 0;    }};

参考了discuss,它采用的是递归的方法,参考其方法求解。最终AC代码,发现运行时间缩短了好多。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int countNodes(TreeNode* root) {        if(root==NULL)            return 0;        int left=0;        int right=0;        TreeNode* temp=root;        while(temp!=NULL)        {            temp=temp->left;            left++;        }        temp=root;        while(temp!=NULL)        {            temp=temp->right;            right++;        }        if(left==right)            return pow(2,left)-1;        else        {            return 1+countNodes(root->left)+countNodes(root->right);        }    }};
0 0
原创粉丝点击