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

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

501. Find Mode in Binary Search Tree

2019-11-09 19:25:06
字體:
來源:轉載
供稿:網友

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);    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 麦盖提县| 漾濞| 南开区| 荔浦县| 高阳县| 辽源市| 外汇| 泌阳县| 马山县| 吉木乃县| 和平区| 樟树市| 沛县| 沧州市| 奉节县| 富锦市| 睢宁县| 彰化市| 新兴县| 伊金霍洛旗| 响水县| 绥江县| 阿合奇县| 涿鹿县| 拜城县| 桦川县| 宝坻区| 蒙城县| 罗定市| 讷河市| 蛟河市| 枣强县| 南充市| 建阳市| 离岛区| 克山县| 绥化市| 和林格尔县| 万年县| 江达县| 衢州市|