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));
    	}
    }
    
  • 相关阅读:
    移动端HTML5音频与视频问题及解决方案
    git did not exit cleanly
    移动端事件对象touches的误区
    原创:CSS3技术-雪碧图自适应缩放与精灵动画方案
    H5+JS+CSS3 综合应用
    深入理解CSS3 Animation 帧动画
    在 MacOS 中使用 multipass 安装 microk8s 环境
    [译] Design patterns for container-based distributed systems
    Sangmado 公共基础类库
    Redola.Rpc 集成 Consul 服务发现
  • 原文地址:https://www.cnblogs.com/denggelin/p/12128022.html
Copyright © 2011-2022 走看看