思路:
用一个数组计数,全部memset为0 ,然后前序遍历二叉树计数,最后再遍历一遍数组,然后不为0 就+1
/**
* 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 {
private:
void preorder(int *hash,TreeNode*root2)
{
if(root2)//不为空
{
hash[root2->val]++;
preorder(hash,root2->right);
preorder(hash,root2->left);
}
}
public:
int numColor(TreeNode* root) {
//用数组计数的方法
int hash[1001];
memset(hash,0,sizeof(hash));
int count=0;
preorder(hash,root);//前序遍历
for(int i=1;i<1001;i++)
{
if(hash[i])
count++;
}
return count;
}
};
如有错误,多多指教!