LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)
Posted SomnusMistletoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)相关的知识,希望对你有一定的参考价值。
题意:寻找二叉查找树中出现次数最多的值
/** * 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 ma = 0; int cnt = 1; TreeNode *pre = NULL; vector<int> ans; void inorder(TreeNode* root){ if(root == NULL) return; inorder(root -> left); if(pre){ if(pre -> val == root -> val){ ++cnt; } else{ if(cnt > ma){ ma = cnt; ans.clear(); ans.push_back(pre -> val); } else if(cnt == ma){ ans.push_back(pre -> val); } cnt = 1; } } pre = root; inorder(root -> right); } vector<int> findMode(TreeNode* root) { if(root == NULL) return ans; inorder(root); if(cnt > ma){ ans.clear(); ans.push_back(pre -> val); } else if(cnt == ma){ ans.push_back(pre -> val); } return ans; } };
以上是关于LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
leetcode501. Find Mode in Binary Search Tree
LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)
[LeetCode]501. Find Mode in Binary Search Tree二叉搜索树寻找众数
LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)