LeetCode-173. Binary Search Tree Iterator (JAVA)BST的迭代

173. Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

用一个Stack记录从根节点到当前节点的路径。next的时候就返回Stack最上面的元素。不过拿出最上面的元素后,我们还要看一下这个被返回的元素是否有右节点,如果有的话,就把它的右节点及右节点的所有左边节点都压入栈中。另外,初始化栈时,我们要找到最左边的节点,也就是中序遍历的第一个节点,并把根到第一个节点的路径都压入栈。

本题目的本质是二叉树的中序遍历

public class BSTIterator {
	private Stack<TreeNode> stk;
	public BSTIterator(TreeNode root) {
		stk = new Stack<>();
		// 先找到第一个节点,并把路径入栈
		while (root != null) {
			stk.push(root);
			root = root.left;
		}

	}

	/**
	 * @return whether we have a next smallest number
	 */
	public boolean hasNext() {
		// 栈为空时不再有下一个
		return !stk.isEmpty();

	}

	/**
	 * @return the next smallest number
	 */
	public int next() {
		TreeNode curr = stk.pop();
		int res = curr.val;
		// 如果该元素有右节点,把它的右节点及右节点的所有左边节点都压入栈中
		curr = curr.right;
		while (curr != null) {
			stk.push(curr);
			curr = curr.left;
		}
		return res;

	}
}

二叉树的中序遍历非递归

public List<Integer> inorderTraversal(TreeNode root) {  
        List<Integer> list = new ArrayList<>();  
        if (root == null)  
            return list;  
        Stack<TreeNode> stack = new Stack<>();  
        while (root != null || !stack.isEmpty()) {  
            if (root != null) {  
                stack.push(root);  
                root = root.left;  
            } else {  
                root = stack.pop();  
                list.add(root.val);  
                root = root.right;  
            }  
        }  
        return list;  
    } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值