Leetcode二叉树 501. 二叉搜索树中的众数

遍历


package binarytree.findMode;

import binarytree.untils.GenerateTreeNode;
import binarytree.untils.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 501. 二叉搜索树中的众数
 * 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
 *
 * 假定 BST 有如下定义:
 *
 * 结点左子树中所含结点的值小于等于当前结点的值
 * 结点右子树中所含结点的值大于等于当前结点的值
 * 左子树和右子树都是二叉搜索树
 * 例如:
 * 给定 BST [1,null,2,2],
 *
 *    1
 *     \
 *      2
 *     /
 *    2
 * 返回[2].
 *
 * 提示:如果众数超过1个,不需考虑输出顺序
 */
public class findMode {
    /**
     * 搜索遍历
     * @param root
     * @return
     */
    public static int[] findMode(TreeNode root) {
        Map<Integer,Integer> map = new HashMap<>();
        inOrder(root,map);
        int max = 0;
        for (Map.Entry<Integer,Integer> m: map.entrySet()) {
            max=Math.max(max,m.getValue());
        }

       List<Integer> res1 = new ArrayList<>();
        int i = 0;
        for (Map.Entry<Integer,Integer> m: map.entrySet()) {
          if(m.getValue()==max){
              res1.add(m.getKey());
          }
        }

       int[] res = new int[res1.size()];
        for (int j = 0; j < res1.size(); j++) {
            res[j] = res1.get(j);
        }


        return res;
    }
    
    private static void inOrder(TreeNode root,Map<Integer,Integer> map){
      if(root == null){
          return;
      }
        if(map.containsKey(root.val)){
            int count = map.get(root.val);
            map.put(root.val,++count);
        }
        else{
            map.put(root.val,1);
        }
        inOrder(root.left,map);
        inOrder(root.right,map);
    }

    public static void main(String[] args) {
        Integer[] nums = {1,null,2};
        TreeNode treeNode = GenerateTreeNode.generateTreeNode(nums);
        int[] mode = findMode(treeNode);
        for (int i = 0; i < mode.length; i++) {
            System.out.println(mode[i]);
        }
    }
}

原文地址:https://www.cnblogs.com/xiaoshahai/p/15701145.html