LeetCode501. 二叉搜索树中的众数

思路

二叉搜索树就要想到把二叉搜索树的中序遍历结果为单调递增的队列,所以,先得到中序遍历的结果,再从中序遍历的结果中寻找众数,最后将众数打印出来即可。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int[] findMode(TreeNode root) {
        
        List list = new ArrayList<>();
        fun(root,list);
        int[] s = new int[1];
        if(list.size() == 1){
            s[0] = root.val;
            return s;
        }
        Map res = new HashMap();
        int max = 0;
        for(int i =0;i sum = new ArrayList<>();
        int j = 0;
        //遍历map的key并得到对应的value,将value与max比较即可
        for(int i:res.keySet()){
            if(res.get(i) == max){
                sum.add(i);
            }
        }
        int[] ss = new int[sum.size()];
        for(int i =0;i

你可能感兴趣的:(LeetCode,leetcode,二叉树)