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));
    	}
    }
    
  • 相关阅读:
    我这些年的项目管理心得...
    14条建议,使你的IT职业生涯更上一层楼
    手机通过WIFI连上ZXV10 H618B路由器但不能上网问题的解决
    优秀中层必备的十大能力
    IMX51启动模式
    VS2005工程由Pocket PC 2003 SDK转为WINCE6.0 SDK的问题
    VS2005工程增加SDK
    VS2005下开发PPC2003和WM50编译器一些设置
    CTO俱乐部下午茶:技术团队管理中的那些事儿
    Android通过JNI调用驱动程序(完全解析实例)
  • 原文地址:https://www.cnblogs.com/denggelin/p/12128022.html
Copyright © 2011-2022 走看看