2 0 1 9 -5 -4 星 期六 开 始 吧
上 一 题 链 接 Leetcode基础刷题之 PHP 解析( 144. 145)
题 目 描 述
检验一个树是不是二叉查找树
题 目 分 析
思路有两种,二叉查找树的特点就是左子树上的结点都小于根结点,右子树上的结点都大于根节点。所以有两个方向,可以分别递归的判断左子树,右子树。或者拿左子树上的最大值,右子树上的最小值分别对应根结点进行判断。
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return Boolean
*/
function isValidBST($root) {
return $this->helper($root,null,null);
}
function helper($root,$lower,$upper){
if($root==null) return true;
$res=$root->val;
if($lower !==null && $res<=$lower) return false;
if($upper !==null && $res>=$upper) return false;
if(!$this->helper($root->left,$lower,$res)) return false;
if(!$this->helper($root->right,$res,$upper)) return false;
return true;
}
}
Github整理地址:https://github.com/wuqinqiang/leetcode-php
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Apache Flink 零基础入门(一):基础概念解析
- Apache Flink 零基础入门(一):基础概念解析
- JStorm 源码解析:基础线程模型
- React Hooks 解析(上):基础
- TypeScript基础入门之模块解析(一)
- TypeScript基础入门之模块解析(二)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Machine Learning in Action
Peter Harrington / Manning Publications / 2012-4-19 / GBP 29.99
It's been said that data is the new "dirt"—the raw material from which and on which you build the structures of the modern world. And like dirt, data can seem like a limitless, undifferentiated mass. ......一起来看看 《Machine Learning in Action》 这本书的介绍吧!