98.Validate Binary Search Tree&检查是否为BST
2015-06-29 11:35
295 查看
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.
中序遍历二叉树,检查得到的序列是否是升序。
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.
中序遍历二叉树,检查得到的序列是否是升序。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { if(!root) return true; stack<TreeNode * > s; TreeNode *p = root; vector<int> ret; while(p != 0 || !s.empty()) { while(p != 0) { s.push(p); p = p -> left; } if(!s.empty()) { p = s.top(); ret.push_back(p -> val); s.pop(); p = p -> right; } } for(int i = ret.size() - 1;i>=1;i--) { if(ret[i] <= ret[i-1]) return false; } return true; } };
class Checker { public: bool checkBST(TreeNode* root) { // write code here if(!root) return false; vector<int> vals; middleOrderNonRecurisive(root,vals); for(int i = 0;i<vals.size()-1;++i) { if(vals[i] >= vals[i+1]) return false; } return true; } void middleOrderRecursive(TreeNode *root,vector<int> &vals) { if(root) { middleOrderRecursive(root->left,vals); vals.push_back(root->val); middleOrderRecursive(root->right,vals); } } void middleOrderNonRecurisive(TreeNode *root,vector<int> &vals) { if(!root) return; stack<TreeNode *> pStack; while(root || !pStack.empty()) { while(root) { pStack.push(root); root = root->left; } if(!pStack.empty()) { root = pStack.top(); pStack.pop(); vals.push_back(root->val); root = root->right; } } } };
相关文章推荐
- 考试系统维护所感
- PHP高并发高负载系统架构例子
- 3D数学基础--3D中的方位与角位移(1)
- vassistx配置
- 3D数学基础--3D中的方位与角位移(1)
- GRE新填空技巧:感情色彩解法
- Java Web 经典开发模式
- system ():
- No setter found for property 'adService' in class 'com.shop.action.AdAction'
- HTTP 学习手册
- java实现爬虫爬网站图片
- C/C++中extern关键字详解
- java中利用jar包将list,对象等转换为json数据格式
- 十步图解css的position
- delegate用法
- 快捷键
- iOS 隐藏状态栏
- Linux下数据流重导向(Redirection)
- C#实现导入CSV文件到Excel工作簿的方法
- ubuntu14.04交叉编译vlc2.1.5源码,编译出在win32下运行的程序