diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index b555692f..385ce2f1 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -344,46 +344,53 @@ public: Java: -```java + +```Java class Solution { - private LinkedList list = new LinkedList<>(); - private int currentValue; - private int count; - private int maxCount; + ArrayList resList; + int maxCount; + int count; + TreeNode pre; + public int[] findMode(TreeNode root) { - count = 0; + resList = new ArrayList<>(); maxCount = 0; - currentValue = root.val; - findModeTrl(root); - int[] res = new int[list.size()]; - for (int i = 0; i < res.length; i++) { - res[i] = list.get(i); + count = 0; + pre = null; + findMode1(root); + int[] res = new int[resList.size()]; + for (int i = 0; i < resList.size(); i++) { + res[i] = resList.get(i); } return res; } - private void findModeTrl (TreeNode root) { - if (root == null) return; - findModeTrl(root.left); - if (root.val == currentValue) { - count++; - } else { - currentValue = root.val; + public void findMode1(TreeNode root) { + if (root == null) { + return; + } + findMode1(root.left); + + int rootValue = root.val; + // 计数 + if (pre == null || rootValue != pre.val) { count = 1; + } else { + count++; } - - if (count == maxCount) { - list.add(root.val); - } else if (count > maxCount) { + // 更新结果以及maxCount + if (count > maxCount) { + resList.clear(); + resList.add(rootValue); maxCount = count; - list.clear(); - list.add(currentValue); + } else if (count == maxCount) { + resList.add(rootValue); } + pre = root; - findModeTrl(root.right); + findMode1(root.right); } } - ``` Python: