首页 > 其他 > 详细

【题解】【BST】【Leetcode】Validate Binary Search Tree

时间:2014-02-03 12:57:59      阅读:404      评论:0      收藏:0      [点我收藏+]

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 keys less than the node‘s key.
  • The right subtree of a node contains only nodes with keys greater than the node‘s key.
  • Both the left and right subtrees must also be binary search trees.

思路:

这题其实考查的是BST的定义,下面code的是CC150v5上的第一种答案简化版,同样借鉴中序遍历的思想,但是只保存当前点上家的值,判断当前点是否大于上家。

代码:

bubuko.com,布布扣
 1 bool isValidBST(TreeNode *root) {
 2     int init = INT_MIN;
 3     return isValidNode(root, init);
 4 }
 5 bool isValidNode(TreeNode *root, int& lastVal){
 6     if(root == NULL)
 7         return true;
 8 
 9     if(!isValidNode(root->left, lastVal))
10         return false;
11         
12     if(root->val <= lastVal) //不是<而是<=,failed {1,1}=>false
13         return false;
14     lastVal = root->val;
15     
16     if(!isValidNode(root->right, lastVal))
17         return false;
18     
19     return true;//忘写最后一句了
20 }
bubuko.com,布布扣

【题解】【BST】【Leetcode】Validate Binary Search Tree

原文:http://www.cnblogs.com/wei-li/p/ValidateBinarySearchTree.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!