Binary Search Tree Iterator

/*
另外一种节省空间复杂度的方法 就是声明一个stack 先把左边的节点全都写入 stack 在next()中 每次pop出一个后 再把有节点加入stack中
*/
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class BSTIterator {
    
    private Stack<TreeNode> stack;
    
    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        while(root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode node = stack.pop();
        if(node.right != null) {
            TreeNode temp = node.right;
            while(temp != null) {
                stack.push(temp);
                temp = temp.left;
            }
        }
        return node.val;
    }
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */


// /*
// 如果不考虑空间复杂度的问题; 此题可变为二叉树的中序遍历问题;建立一个queue 用于储存 遍历好的二叉树 然后 依次往出拿;
// */
// /**
//  * Definition for binary tree
//  * public class TreeNode {
//  *     int val;
//  *     TreeNode left;
//  *     TreeNode right;
//  *     TreeNode(int x) { val = x; }
//  * }
//  */


// public class BSTIterator {
    
//     private Queue<Integer> q;
    
//     public BSTIterator(TreeNode root) {
//         q = new LinkedList<Integer>();
//         Stack<TreeNode> stack = new Stack<TreeNode>();
//         TreeNode node = root;
//         while(node != null || !stack.isEmpty()) {
//             if(node != null) {
//                 stack.push(node);
//                 node = node.left;
//             } else {
//                 node = stack.pop();
//                 q.offer(node.val);
//                 node = node.right;
//             }
//         }
//     }

//     /** @return whether we have a next smallest number */
//     public boolean hasNext() {
//         return !q.isEmpty();
//     }

//     /** @return the next smallest number */
//     public int next() {
//         if(hasNext()) {
//             return q.poll();
//         } else {
//             return -1;
//         }
//     }
// }

// /**
//  * Your BSTIterator will be called like this:
//  * BSTIterator i = new BSTIterator(root);
//  * while (i.hasNext()) v[f()] = i.next();
//  */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值