当前位置: 首页 > 后端技术 > Java

LeetCode-173-BinarySearchTreeIterator

时间:2023-04-01 22:37:44 Java

BinarySearchTreeIterator题目描述:实现一个二叉搜索树迭代器类BSTIerator,代表一个按顺序遍历二叉搜索树(BST)的迭代器:BSTIerator(TreeNoderoot)初始化一个BSTIerator类的对象。BST的根节点root作为构造函数的一部分给出。该指针应初始化为一个不存在于BST中且小于BST中任何元素的数字。booleanhasNext()如果指针右边有数字则返回真;否则返回false。intnext()将指针向右移动并返回指针处的数字。请注意,指针被初始化为BST中不存在的数字,因此第一次调用next()将返回BST中的最小元素。可以假设next()调用总是有效的,即当调用next()时,在BST的中序遍历中至少存在下一个数字。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:中序遍历首先在BSTIerator中声明一个List作为values来存放二叉树的节点值,在构造方法中通过中序遍历将节点值初始化为values.然后,声明一个索引来标识当前位置,next()方法和hasNext()方法的实现依赖于索引和值进行判断。importcom.kaesar.leetcode.TreeNode;importjava.util.ArrayList;importjava.util.List;publicclassLeetCode_173{publicstaticvoidmain(String[]args){//测试用例TreeNoderoot=newTreeNode(7);root.left=newTreeNode(3);root.right=newTreeNode(15);root.right.left=newTreeNode(9);root.right.right=newTreeNode(20);BSTIteratorbSTIterator=newBSTIterator(root);System.out.println(bSTIterator.next());//返回3System.out.println(bSTIterator.next());//返回7System.out.println(bSTIterator.hasNext());//返回TrueSystem.out.println(bSTIterator.next());//返回9System.out.println(bSTIterator.hasNext());//返回TrueSystem.out.println(bSTIterator.next());//返回15System.out.println(bSTIterator.hasNext());//返回TrueSystem.out.println(bSTIterator.next());//返回20System.out.println(bSTIterator.hasNext());//返回False}}classBSTIerator{privateintindex;私有列表<整数>值;publicBSTIerator(TreeNoderoot){this.index=0;this.values=newArrayList<>();inOrder(根,值);}/***中序遍历**@paramroot*@paramvalues*/privatevoidinOrder(TreeNoderoot,Listvalues){if(root==null){return;}inOrder(root.left,values);值.add(root.val);inOrder(root.right,值);}publicintnext(){returnvalues.get(index++);}publicbooleanhasNext(){returnindex