解题思路:

morris遍历先中序把整棵树遍历一遍


提交代码:

class BSTIterator {
	private List<Integer> nums=new ArrayList<Integer>();
	private int p=0;
	
    public BSTIterator(TreeNode root) {
        TreeNode cur=root,tmp=root;
        
        while(cur!=null) {
        	if(cur.left!=null) {
        		tmp=cur.left;
        		while(tmp.right!=null&&tmp.right!=cur)
        			tmp=tmp.right;
        
        			if(tmp.right==null) {
        				tmp.right=cur;
        				cur=cur.left;
        			}else {
        				nums.add(cur.val);
        				cur=cur.right;
        			}
        
        	}else {
        		nums.add(cur.val);
        		cur=cur.right;
        	}
        }
    }
    
    /** @return the next smallest number */
    public int next() {
        return nums.get(p++);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        if(p<nums.size())	return true;
        return false;
    }
}

运行结果:

【leetcode】173.(Medium)Binary Search Tree Iterator

相关文章:

  • 2021-06-10
  • 2021-11-01
  • 2022-02-12
  • 2021-10-08
  • 2022-02-04
  • 2022-12-23
猜你喜欢
  • 2021-08-12
  • 2021-04-06
  • 2021-07-08
  • 2021-10-23
  • 2021-10-15
  • 2022-12-23
  • 2022-01-10
相关资源
相似解决方案