Java avg O(1)time, O(1) memory Morris Traversal Iterator


  • 0
    X
    public class BSTIterator {
    
        TreeNode pre = null;
        public BSTIterator(TreeNode root) {
            while (root != null) {//go to leftmost leave while keeping build right links for every left child
                if (root.left != null) {
                    TreeNode tmp = root.left;
                    while (tmp.right != null) {
                        tmp = tmp.right;
                    }
                    tmp.right = root;
                    root = root.left;
                }
                else {
                    pre = root;
                    break;
                }
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return pre != null;
        }
    
        /** @return the next smallest number */
        public int next() {
            int ans = pre.val;
            pre = pre.right;//go to right first
            while (pre != null){
                if (pre.left != null) {
                    TreeNode tmp = pre.left;
                    while (tmp.right != null && tmp.right != pre) {
                        tmp = tmp.right;
                    }
                    if (tmp.right == pre) {//if it go along the built line, delete the line and return
                        tmp.right = null;
                        break;
                    }
                    else {
                        tmp.right = pre; //if it go right along the original line, it need to go to leftmost while keeping building right line for every child
                        pre = pre.left;
                    }
                }
                else {
                    break;
                }
            }
            return ans;
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.