这个题我们可以用数组辅助完成,然后进行排序后,再用再进行取值,这是我的代码块:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/void Preorder_trave(struct TreeNode* root,int* number,int* length){if(root == NULL)return;number[(*length)++] = root->val;Preorder_trave(root->left,number,length);Preorder_trave(root->right,number,length);}int compare(const void* a,const void* b){return *(int*)a - *(int*)b;}
int findSecondMinimumValue(struct TreeNode* root) {//创立数组int* number = (int*)malloc(sizeof(int) * 25);//创立数组长度int* length = (int*)malloc(sizeof(int));*length = 0;//使用前序遍历,把结点存入数组中Preorder_trave(root,number,length);int judge = number[0];int k = 0;int i = 0;//判断每个结点是否相同for(i = 0;i < *length;i++){if(number[i] == judge)k++;}if(k == *length)return -1;//进行qsort排序qsort(number,*length,sizeof(int),compare);//取第二个最小的值for(i = 0;i < *length - 1;i++){if(number[i] != number[i + 1])break;}return number[i + 1];
}
我这个方法比较通俗易懂,但时间复杂度比较高,大家如果觉得好的话,就请给个免费的赞吧!谢谢了^ _ ^