• Find mode in Binary Search Tree


    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).

    Solution: 题目要求O(1)的空间复杂度,所以我们需要先得到有多少个modes,再申请空间。所产生的stack space不计入空间复杂度,因此可用递归。

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     private int currentModes = 0;
    12     private int currentValue = 0;
    13     private int currentCount = 0;
    14     private int modes[];
    15     private int maxCount = 0;
    16     
    17     public int[] findMode (TreeNode root) {
    18         helper(root);
    19         modes = new int[currentModes];
    20         currentModes = 0;
    21         currentCount = 0;
    22         helper(root);
    23         return modes;
    24     }
    25     
    26     private void helper (TreeNode root) {
    27         if (root == null) return;
    28         
    29         helper(root.left);
    30         
    31         if (root.val != currentValue) {
    32             currentCount = 1;
    33             currentValue = root.val;
    34         } else {
    35             currentCount++;
    36         }
    37         
    38         if (currentCount > maxCount) {
    39             maxCount = currentCount;
    40             currentModes = 1;
    41         } else if (currentCount == maxCount) {
    42             if (modes != null)
    43                 modes[currentModes] = root.val;
    44             currentModes++;
    45         }
    46         
    47         helper(root.right);
    48     }
    49 }
  • 相关阅读:
    二分法查找数据
    循环队列的操作
    堆栈的操作
    链表的各种操作
    尾插法创建链表
    头插法创建链表
    链表简介
    <map>的常用操作
    linux下php添加自带扩展
    快速排序
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6395229.html
Copyright © 2020-2023  润新知