zoukankan      html  css  js  c++  java
  • LeetCode_501. Find Mode in Binary Search Tree

    501. Find Mode in Binary Search Tree

    Easy

    Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

    Assume a BST is defined as follows:

    • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
    • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
    • Both the left and right subtrees must also be binary search trees.

    For example:
    Given BST [1,null,2,2],

       1
        
         2
        /
       2
    

    return [2].

    Note: If a tree has more than one mode, you can return them in any order.

    Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

    package leetcode.easy;
    
    /**
     * Definition for a binary tree node. public class TreeNode { int val; TreeNode
     * left; TreeNode right; TreeNode(int x) { val = x; } }
     */
    public class FindModeInBinarySearchTree {
    	private static void print_arr(int[] nums) {
    		for (int num : nums) {
    			System.out.print(num + " ");
    		}
    		System.out.println();
    	}
    
    	java.util.Map<Integer, Integer> map;
    	int max = 0;
    
    	public int[] findMode(TreeNode root) {
    		this.map = new java.util.HashMap<>();
    		inorder(root);
    		java.util.List<Integer> list = new java.util.LinkedList<>();
    		for (int key : map.keySet()) {
    			if (map.get(key) == max) {
    				list.add(key);
    			}
    		}
    		int[] num = new int[list.size()];
    		for (int i = 0; i < list.size(); i++) {
    			num[i] = list.get(i);
    		}
    		return num;
    	}
    
    	public void inorder(TreeNode root) {
    		if (root == null) {
    			return;
    		}
    		map.put(root.val, map.getOrDefault(root.val, 0) + 1);
    		if (map.get(root.val) > max) {
    			max = map.get(root.val);
    		}
    		inorder(root.left);
    		inorder(root.right);
    	}
    
    	@org.junit.Test
    	public void test() {
    		TreeNode tn11 = new TreeNode(1);
    		TreeNode tn22 = new TreeNode(2);
    		TreeNode tn33 = new TreeNode(2);
    		tn11.left = null;
    		tn11.right = tn22;
    		tn22.left = tn33;
    		tn22.right = null;
    		tn33.left = null;
    		tn33.right = null;
    		print_arr(findMode(tn11));
    	}
    }
    
  • 相关阅读:
    uva11059
    uva725
    程序中double类型的数输出为什么要用lf
    c++形参和实参同名时,如何单步执行观察形参的变化。
    台式机的字母键和数字键都不能正常使用了呢?
    找错误——下面的程序意图在于统计字符串中字符数1的个数,可惜有瑕疵
    初学者常见错误1——赋值时的类型转换
    scanf
    c++的调试与运行
    黑猫派对
  • 原文地址:https://www.cnblogs.com/denggelin/p/12128022.html
Copyright © 2011-2022 走看看