Lintcode95 Validate Binary Search Tree solution 题解

【题目描述】

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

·The left subtree of a node contains only nodes with keysless thanthe node's key.

·The right subtree of a node contains only nodes with keysgreater thanthe node's key.

·Both the left and right subtrees must also be binary search trees.

·A single node tree is a BST

给定一个二叉树,判断它是否是合法的二叉查找树(BST)

一棵BST定义为:

·节点的左子树中的值要严格小于该节点的值。

·节点的右子树中的值要严格大于该节点的值。

·左右子树也必须是二叉查找树。

·一个节点的树也是二叉查找树。

【题目链接】

www.lintcode.com/en/problem/validate-binary-search-tree/

【题目解析】

对于如何处理复杂边界条件,有两种有效的方法:

1.引入dummy node,这个对于链表头不确定时特别有效。

2.引入INT_MAX,INT_MIN等最大/最小值,对于比较类问题很有效(需要考虑到本身值就为最值,这种情况一般极少见)。

显然,对于这个问题,dummy node是不太适用,我们来探讨下取最值的可能性。从以上代码可知边界处理的关键在于需要判断root->left和root-right是否为NULL,key的比较则相对固定,分别为root->left->val和root->right->val, 由此我们自然可以联想到可以使用left_val和right_val对左右子树的key进行「包装」,在子节点与根节点的key进行比较之前对l eft_val和right_val赋值即可(这一思想在lintcode:(65) Median of two Sorted Arrays和lintcode:(93) Balanced Binary Tree中也有使用)。

【参考答案】

www.jiuzhang.com/solutions/validate-binary-search-tree/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值