1. 程式人生 > >leetcode[Find Mode in Binary Search Tree]//待整理多種解法

leetcode[Find Mode in Binary Search Tree]//待整理多種解法

解法一:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	private void recurse(TreeNode root, Map<Integer, Integer> map){
		if(root == null){
			return;
		}
        //System.out.println(root.val);
		map.put(root.val, map.getOrDefault(root.val, 0) + 1);
		TreeNode left = root.left;
		TreeNode right = root.right;
		recurse(left,map);
		recurse(right,map);
	}
	
    public int[] findMode(TreeNode root) {
        //既然都是二分查詢樹了,說明中根遍歷肯定是有序的了,可以利用這個來作文章
    	//現在先採用普通方法(適用於任意二叉樹),來找出二叉樹中出現次數最多的結點的值
    	//利用HashMap來統計樹中結點的值的出現次數
    	HashMap<Integer,Integer> map = new HashMap<>();
    	recurse(root, map);
    	
    	if(root == null){//空樹單獨處理,不是返回null,二十返回[]
    		return new int[0];
    	}
    	
    	Iterator<Integer> it = map.values().iterator();
    	
    	//因為空樹已經單獨處理了,此時it一定有元素
    	int mostFrequent = it.next();//找出二叉樹中出現次數最多的結點的值的出現次數
    	while(it.hasNext()){
    		mostFrequent = Math.max(mostFrequent, it.next());
    	}
    	
        //System.out.println(mostFrequent);
    	
    	List<Integer> resList = new ArrayList<>();
    	for(Map.Entry<Integer, Integer> entry : map.entrySet()){
    		if(entry.getValue() == mostFrequent){
    			resList.add(entry.getKey());//將最經常出現的結點的值統計到結果中
    		}
    	}
    	
    	int[] res = new int[resList.size()];
    	for(int i = 0; i < resList.size(); i++){
    		res[i] = resList.get(i);
    	}
    	
    	return res;
    }
}