From da4116bcb60b3bf6efa7f44e8e20877e987fadfe Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Sat, 29 Apr 2023 05:45:01 -0400 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20Java=20=E7=B5=B1=E4=B8=80?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 Java 統一迭代法 --- problems/0501.二叉搜索树中的众数.md | 53 ++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index b7ef606f..e467bf8a 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -472,6 +472,59 @@ class Solution { } } ``` +統一迭代法 +```Java +class Solution { + public int[] findMode(TreeNode root) { + int count = 0; + int maxCount = 0; + TreeNode pre = null; + LinkedList res = new LinkedList<>(); + Stack stack = new Stack<>(); + + if(root != null) + stack.add(root); + + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + if(curr != null){ + stack.pop(); + if(curr.right != null) + stack.add(curr.right); + stack.add(curr); + stack.add(null); + if(curr.left != null) + stack.add(curr.left); + }else{ + stack.pop(); + TreeNode temp = stack.pop(); + if(pre == null) + count = 1; + else if(pre != null && pre.val == temp.val) + count++; + else + count = 1; + pre = temp; + if(count == maxCount) + res.add(temp.val); + if(count > maxCount){ + maxCount = count; + res.clear(); + res.add(temp.val); + } + } + } + int[] result = new int[res.size()]; + int i = 0; + for (int x : res){ + result[i] = x; + i++; + } + return result; + } +} +``` + ## Python