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