验证二叉搜索树

https://leetcode-cn.com/problems/validate-binary-search-tree/

  1. /*中序遍历将所有元素升序输出*/
  2. class Solution {
  3. Stack<TreeNode> s;
  4. int last;
  5. boolean flag = true;
  6. Solution(){
  7. s = new Stack<TreeNode>();
  8. }
  9. public boolean trans(TreeNode root){
  10. while(root != null || !s.isEmpty()){
  11. while(root != null){
  12. s.add(root);
  13. root = root.left;
  14. }
  15. if(!s.isEmpty()){
  16. root = s.pop();
  17. if(!flag){
  18. if(last >= root.val)
  19. return false;
  20. last = root.val;
  21. }
  22. else{
  23. last = root.val;
  24. flag = !flag;
  25. }
  26. root = root.right;
  27. }
  28. }
  29. return true;
  30. }
  31. public boolean isValidBST(TreeNode root) {
  32. return trans(root);
  33. }
  34. }

二叉搜索树迭代器

https://leetcode-cn.com/problems/binary-search-tree-iterator/

  1. class BSTIterator {
  2. Stack<TreeNode> s;
  3. TreeNode root;
  4. public BSTIterator(TreeNode root) {
  5. s = new Stack<TreeNode>();
  6. this.root = root;
  7. }
  8. public int next() {
  9. while(root != null){
  10. s.add(root);
  11. root = root.left;
  12. }
  13. root = s.pop();
  14. int r = root.val;
  15. root = root.right;
  16. return r;
  17. }
  18. public boolean hasNext() {
  19. return (root != null || !s.isEmpty());
  20. }
  21. }