今天的这篇page是针对leetcode501.二叉搜索树中的众数所写的。小尼先简单的说明一下这道题的意思,给出一个含重复值的二叉搜索树(BST)的根节点root,找出并返回BST中的所有众数。这里面的思路其实和上一篇文章运用的思路是一样的,都是利用一个比较的思路求解。
小尼首先给出递归的解法,首先就是我们定义一个count数值用于记录重复项的个数,然后我们不断与我们之前取到的maxCount的值进行比较,当大于时我们的maxCount就去用count取代,小尼接下来给出代码:
class Solution { ArrayList<Integer> reList; int maxCount; int count; TreeNode pre; public int[] findMode(TreeNode root) { reList = new ArrayList<>(); maxCount = 0; count = 0; pre = null; findMode1(root); int[] res = new int[reList.size()]; for(int i = 0;i<reList.size();i++){ res[i] = reList.get(i); } return res; } 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) { reList.clear(); reList.add(rootValue); maxCount = count; }else if(count == maxCount){ reList.add(rootValue); } pre = root; findMode1(root.right); } }
小尼接下来给出迭代法的代码:
class Solution { public int[] findMode(TreeNode root) { TreeNode pre = null; Stack<TreeNode> stack = new Stack<>(); List<Integer> result = new ArrayList<>(); int maxCount = 0; int count = 0; TreeNode cur = root; while (cur != null || !stack.isEmpty()) { if (cur != null) { stack.push(cur); cur =cur.left; }else { cur = stack.pop(); // 计数 if (pre == null || cur.val != pre.val) { count = 1; }else { count++; } // 更新结果 if (count > maxCount) { maxCount = count; result.clear(); result.add(cur.val); }else if (count == maxCount) { result.add(cur.val); } pre = cur; cur = cur.right; } } return result.stream().mapToInt(Integer::intValue).toArray(); } }
其实迭代法的解法根递归的区别不是很大,迭代法这边只是使用while循环代替了上面的递归的作用,其他语句的使用差别不大