[Java] 173. Binary search tree iterator---learning binary tree in-order sequence, avoid stepping on pits! ! !

Implement a binary search tree iterator class BSTIterator, which represents an iterator that traverses the binary search tree (BST) in the middle order:
BSTIterator (TreeNode root) initializes an object of the BSTIterator class. The root node root of the BST will be given as part of the constructor. The pointer should be initialized to a number that does not exist in the BST, and the number is less than any element in the BST.
boolean hasNext() Returns true if there are numbers traversing to the right of the pointer; otherwise, returns false.
int next() moves the pointer to the right, and then returns the number at the pointer.
Note that the pointer is initialized to a number that does not exist in the BST, so the first call to next() will return the smallest element in the BST.

You can assume that the next() call is always valid, that is, when next() is called, there is at least one next number in the in-order traversal of the BST.

Example:

Insert picture description here

输入
[“BSTIterator”, “next”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
输出
[null, 3, 7, true, 9, true, 15, true, 20, false]

Interpret
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False

prompt:

The number of nodes in the tree is within the range [1, 105]
0 <= Node.val <= 106
Call hasNext and next operations up to 105 times

Advanced:

Can you design a solution that meets the following conditions? The next() and hasNext() operations share the time complexity of O(1) and use O(h) memory. Where h is the height of the tree.

代码:
private List<Integer> list=new ArrayList<Integer>();
    private void node(TreeNode root) {
    
    
    	if(root==null) {
    
    
    		return;
    	}
    	node(root.left);
    	list.add(root.val);
    	node(root.right);
    }
	public BSTIterator(TreeNode root) {
    
    
       node(root);
    }
    
    public int next() {
    
    
    	if(list.size()>0) {
    
    
    		int a=list.get(0);
    		list.remove(0);
    		return a;
    	}
		return 0;

    }
    public boolean hasNext() {
    
    
    	if(list.size()>0) {
    
    
    		return true;
    	}
		return false;

    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115308783