🌕 173. 二叉搜玢树迭代噚

吞䜛童子2022幎10月10日
  • algorithm
  • tree
小于 1 分钟

🌕 173. 二叉搜玢树迭代噚

隟床: 🌕

问题描述

img_1.png


解法

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class BSTIterator {
    // 思路
    // 䞭序遍历 - 迭代
    TreeNode root;
    LinkedList<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        this.root = root;
        this.stack = new LinkedList<>();
        // 定䜍到 next 銖节点
        TreeNode cur = root;
        if(!stack.isEmpty() || cur != null) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
        }
    }
    
    public int next() {
        TreeNode cur = stack.pop();
        int res = cur.val;
        cur = cur.right;
        if(!stack.isEmpty() || cur != null) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
        }
        return res;
    }
    
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

蟓出

img.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou