leetcode 501. Find Mode in Binary Search Tree

来源:互联网 发布:网络双刃剑政治论文 编辑:程序博客网 时间:2024/06/05 06:19

原题:

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

For example:
Given BST [1,null,2,2],

   1    \     2    /   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).


代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; *//** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* findMode(struct TreeNode* root, int* returnSize) {    if(root==NULL)        return root;    int* max_times;    int* max_num;    int* flag_num;    int* flag_times;    max_times=(int*)malloc(sizeof(int));    max_num=(int*)malloc(sizeof(int)*20000);    flag_num=(int*)malloc(sizeof(int));    flag_times=(int*)malloc(sizeof(int));    *max_times=0;    *flag_times=0;    void findmaxtimes(struct TreeNode* ,int* ,int* ,int* ,int*,int*);    findmaxtimes(root,max_times,max_num,flag_num,flag_times,returnSize);    if(*flag_times>*max_times)    {        *returnSize=1;        return flag_num;    }    if(*flag_times==*max_times)    {        *(max_num+*returnSize)=*flag_num;        *returnSize+=1;    }    return max_num;}void findmaxtimes(struct TreeNode* root,int* max_times,int* max_num,int* flag_num,int* flag_times,int* returnSize){    if(root==NULL)        return;    findmaxtimes(root->left,max_times,max_num,flag_num,flag_times,returnSize);    if(*flag_times==0)        *flag_num=root->val;    if(root->val==*flag_num)        *flag_times+=1;    else    {        if(*flag_times==*max_times)        {            *(max_num+*returnSize)=*flag_num;            *returnSize+=1;        }        if(*flag_times>*max_times)        {            *max_times=*flag_times;            *max_num=*flag_num;            *returnSize=1;        }        *flag_num=root->val;        *flag_times=1;    }        findmaxtimes(root->right,max_times,max_num,flag_num,flag_times,returnSize);    } 

思路其实不难,就是前序遍历,生成出来一个有序数列,然后统计频率就好。

但是要完成他的要求,就要求在遍历过程中完成统计和比较,其实耐心一点不难写。(我第一次写的时候就觉得贼烦。。。)

原创粉丝点击