zoukankan      html  css  js  c++  java
  • leetcode501. 二叉搜索树中的众数 吴丹阳

    leetcode

    题目

    501. 二叉搜索树中的众数

    解法

    主要是考的一个特性: 二叉搜索树的中序遍历结果是递增的数列
    然后就相当于是对一个递增数列求众数的逻辑了

    class Solution {
        private $maxCount = 0;
        private $base = null;
        private $curCount = 0;
        private $ret = [];
    
        /**
         * @param TreeNode $root
         * @return Integer[]
         */
        function findMode($root) {
            $this->mid($root);
            return $this->ret;
        }
    
        public function mid(TreeNode $root) {
            if (empty($root)) {
                return;
            }
    
            if (!empty($root->left)) {
                $this->mid($root->left);
            }
    
    		// 先判断当前值的数量
            if (!is_null($this->base) && $root->val == $this->base) {
                $this->curCount++;
            } else {
                $this->curCount = 1;
            }
    
    		// 当前值数量大于最大数, 覆盖返回值
            if ($this->curCount > $this->maxCount) {
                $this->ret = [$root->val];
                $this->maxCount = $this->curCount;
            } elseif ($this->curCount == $this->maxCount) {
                $this->ret[] = $root->val;
            }
    
            $this->base = $root->val;
    
            if (!empty($root->right)) {
                $this->mid($root->right);
            }
    
        }
    }
    
    

    参考

    本文来自博客园,作者:吴丹阳-cn,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/15758598.html

  • 相关阅读:
    C语言内存分析
    算法之快速排序
    单链表逆转
    C程序设计语言之一
    vim插件配置(一)
    makefile示例
    cocos2d基础入门
    Makefile
    Makefile
    GCC编译四阶段
  • 原文地址:https://www.cnblogs.com/wudanyang/p/15758598.html
Copyright © 2011-2022 走看看