国产探花免费观看_亚洲丰满少妇自慰呻吟_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】永無鄉

下一篇:時鐘項目

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 尼玛县| 兴文县| 班戈县| 磴口县| 安陆市| 若羌县| 康定县| 仁寿县| 太谷县| 吴堡县| 老河口市| 怀化市| 当阳市| 新平| 蒙阴县| 宝兴县| 望奎县| 武夷山市| 屏东县| 银川市| 洛隆县| 济宁市| 雷山县| 象州县| 青岛市| 广宗县| 临夏市| 柘城县| 宝清县| 民丰县| 山阴县| 三门峡市| 游戏| 苏尼特右旗| 遂昌县| 靖西县| 莱芜市| 琼结县| 宁阳县| 东阳市| 衡阳市|