验证二叉搜索树
https://leetcode-cn.com/problems/validate-binary-search-tree/
/*中序遍历将所有元素升序输出*/class Solution {Stack<TreeNode> s;int last;boolean flag = true;Solution(){s = new Stack<TreeNode>();}public boolean trans(TreeNode root){while(root != null || !s.isEmpty()){while(root != null){s.add(root);root = root.left;}if(!s.isEmpty()){root = s.pop();if(!flag){if(last >= root.val)return false;last = root.val;}else{last = root.val;flag = !flag;}root = root.right;}}return true;}public boolean isValidBST(TreeNode root) {return trans(root);}}
二叉搜索树迭代器
https://leetcode-cn.com/problems/binary-search-tree-iterator/
class BSTIterator {Stack<TreeNode> s;TreeNode root;public BSTIterator(TreeNode root) {s = new Stack<TreeNode>();this.root = root;}public int next() {while(root != null){s.add(root);root = root.left;}root = s.pop();int r = root.val;root = root.right;return r;}public boolean hasNext() {return (root != null || !s.isEmpty());}}
