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

解题思路:

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_第1张图片

你可能感兴趣的:(leetcode)