1. 程式人生 > 其它 >碼上來戰!探索“智”感生活,HMS Core線上Codelabs挑戰賽第4期開始!

碼上來戰!探索“智”感生活,HMS Core線上Codelabs挑戰賽第4期開始!

實現一個二叉搜尋樹迭代器類BSTIterator ,表示一個按中序遍歷二叉搜尋樹(BST)的迭代器:
BSTIterator(TreeNode root) 初始化 BSTIterator 類的一個物件。BST 的根節點 root 會作為建構函式的一部分給出。指標應初始化為一個不存在於 BST 中的數字,且該數字小於 BST 中的任何元素。
boolean hasNext() 如果向指標右側遍歷存在數字,則返回 true ;否則返回 false 。
int next()將指標向右移動,然後返回指標處的數字。
注意,指標初始化為一個不存在於 BST 中的數字,所以對 next() 的首次呼叫將返回 BST 中的最小元素。

你可以假設next()呼叫總是有效的,也就是說,當呼叫 next()時,BST 的中序遍歷中至少存在一個下一個數字。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/binary-search-tree-iterator
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。


class BSTIterator {

    private TreeNode root;

    private TreeNode cur;

    public BSTIterator(TreeNode root) {
        this.root = root;
        this.cur = root;
    }

    public int next() {
        while (cur != null) {
            TreeNode mostRight = cur.left;
            if (mostRight != null) {
                while (mostRight.right != null && mostRight.right != cur) {
                    mostRight = mostRight.right;
                }
                if (mostRight.right == null) {
                    mostRight.right = cur;
                    cur = cur.left;
                    continue;
                } else {
                    mostRight.right = null;
                }
            }
            int data = cur.val;
            cur = cur.right;
            return data;
        }
        return -1;
    }

    public boolean hasNext() {
        return this.cur != null;
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
心之所向,素履以往 生如逆旅,一葦以航