博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode: Validata Binary Search Tree
阅读量:7021 次
发布时间:2019-06-28

本文共 1519 字,大约阅读时间需要 5 分钟。

LeetCode: Validata Binary Search Tree

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.

地址:

算法:中序遍历,看看遍历到的节点值是否递增。代码:

1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     bool isValidBST(TreeNode *root) {13         if(!root)   return true;14         stack
stk;15 TreeNode *p = root;16 while(p){17 stk.push(p);18 p = p->left;19 }20 TreeNode *pre = NULL;21 p = NULL;22 while(!stk.empty()){23 pre = p;24 p = stk.top();25 stk.pop();26 if(pre && p->val <= pre->val){27 return false;28 }29 if(p->right){30 TreeNode *q = p->right;31 while(q){32 stk.push(q);33 q = q->left;34 }35 }36 }37 return true;38 }39 };

 

posted on
2014-08-28 22:29 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/boostable/p/leetcode_validate_binary_search_tree.html

你可能感兴趣的文章
php base64图片保存
查看>>
轻松掌握Ajax.net系列教程四:用Ajax.net实现客户端回调(Callback)
查看>>
Kinect+OpenNI学习笔记之3(获取kinect的数据并在Qt中显示的类的设计)
查看>>
整理 读过感觉不错的深度学习博客(更新中)
查看>>
响应在此上下文中不可用
查看>>
4、HTTP(下)
查看>>
redis持久化
查看>>
2017 ACM-ICPC 亚洲区(青岛赛区)网络赛 1009
查看>>
poj3368(RMQ——ST)
查看>>
PHP解说日全食红月
查看>>
mybatis根据property获取column
查看>>
Windows Docker 安装
查看>>
CallableStatement调用Oracle存储过程返回结果集
查看>>
Multi-Model多模数据库引擎设计与实现
查看>>
新建VLAN并启用该VLAN的DHCP功能
查看>>
Python编程进阶
查看>>
python 面向对象反射以及内置方法
查看>>
关于fix shake以及compute命令的应用问题
查看>>
[Interview] string permutation
查看>>
无心准备组会,唯画画能缓解焦虑
查看>>