判断给出的二叉树是否是一个二叉搜索树(BST)
二叉搜索树的定义如下
- 一个节点的左子树上所有节点的值都小于自身的节点值
- 一个节点的右子树上所有节点的值都大于自身的节点值
- 所有节点的左右子树都必须是二叉搜索树
如果你不清楚“{1,#,2,3}"的含义的话,请继续阅读
我们用如下方法将二叉树序列化: 二叉树的序列化遵循层序遍历的原则,”#“代表该位置是一条路径的终结,下面不再存在结点。 例如: 1↵ / ↵ 2 3↵ /↵ 4↵ ↵ 5
上述的二叉树序列化的结果是:"{1,2,3,#,#,4,#,#,5}".
思路:中序遍历获得的是单增的即可
<?php
class Node{
public $left = null;
public $right = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
function isValidBST($root) {
//中序遍历
$arrNode = array();
$arrTmp = array();
array_push($arrNode, $root);
$node = $root;
while (!empty($arrNode)) {
while ($node->left != null) {
array_push($arrNode, $node->left);
$node = $node->left;
}
$node = array_pop($arrNode);
$arrTmp[] = $node->val;
if ($node->right != null) {
array_push($arrNode, $node->right);
$node = $node->right;
}
}
for ($i = 0; $i < count($arrTmp) - 1; $i ++) {
if ($arrTmp[$i] > $arrTmp[$i + 1]) {
return false;
}
}
return true;
}
$node1 = new Node(6);
$node2 = new Node(5);
$node3 = new Node(7);
$node4 = new Node(6);
$node5 = new Node(9);
$node1->left = $node2;
$node1->right = $node3;
$node3->left = $node4;
$node3->right = $node5;
$ret = isValidBST($node1);
print intval($ret);