LeetCode(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.

解题思路:
下面有两种解法,都可以ac,第一种是直接遍历所有的树节点,然后压入栈中,第二种是不压入所有的树节点,一个出栈,才会将该节点右子树的根节点及往下的所有左子节点压入栈,不需要遍历BST

public class BSTIterator {
    Stack<Integer> result;
    public BSTIterator(TreeNode root) {
        result = deal(root);
    }
    public Stack<Integer> deal(TreeNode root){
        Stack<Integer> res = new Stack<Integer>();
        if(root == null)
            return res;
        res.addAll(deal(root.right));
        res.push(root.val);
        res.addAll(deal(root.left));
        return res;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return result.size() != 0 ? true : false;
    }

    /** @return the next smallest number */
    public int next() {
        return result.pop();
    }
}
public class BSTIterator {
    Stack<TreeNode> result;
    public BSTIterator(TreeNode root) {
        result = new Stack<TreeNode>();
        TreeNode temp = root;
        while(temp != null){
            result.push(temp);
            temp = temp.left;
        }
    }
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
       return result.size() != 0 ? true : false;
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode t = result.pop();
        TreeNode temp;
        if(t.right != null){
            result.push(t.right);
            temp = result.peek();
            while(temp.left != null){
                result.push(temp.left);
                temp = temp.left;
            }
        }
        return t.val;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值