国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

501. Find Mode in Binary Search Tree

2019-11-10 17:13:39
字體:
來源:轉載
供稿:網友

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

因為這道題左子節點可能等于根節點和右子節點,宜使用中序遍歷求解。此外,這道題限制空間復雜度O(1),不少sulotion采用hashmap或者list,如果遇到1,2,3,4...n-1,n,n,n的情況,空間復雜度會變成O(n)。所以應該先得到共有幾個modes,再申請空間。代碼如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    PRivate int max = 0;    private int currval = 0;    private int currcount = 0;    private int currmodes = 0;    private int[] modes;        public int[] findMode(TreeNode root) {        helper(root);        modes = new int[currmodes];        currcount = 0;        currmodes = 0;        helper(root);        return modes;    }        public void helper(TreeNode root) {        if (root == null) {            return;        }        helper(root.left);        if (root.val != currval) {            currval = root.val;            currcount = 1;        } else {            currcount ++;        }        if (currcount > max) {            max = currcount;            currmodes = 1;        }else if (currcount == max) {            if (modes != null) {                modes[currmodes] = root.val;            }            currmodes ++;        }        helper(root.right);    }}


上一篇:【Bzoj2733】永無鄉

下一篇:時鐘項目

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阳山县| 西乌| 双城市| 贵州省| 自贡市| 南乐县| 泸水县| 朝阳区| 天柱县| 泰来县| 潼关县| 彰武县| 阳城县| 和田市| 习水县| 翼城县| 元阳县| 桐乡市| 台北市| 佛冈县| 宜川县| 汤原县| 杂多县| 龙游县| 徐闻县| 永靖县| 靖安县| 阆中市| 和林格尔县| 江西省| 辽源市| 滁州市| 绩溪县| 长宁区| 藁城市| 工布江达县| 墨玉县| 新巴尔虎右旗| 东山县| 于田县| 舒城县|