Binary Tree Inorder Traversal, Binary Search Tree Iterator

来源:互联网 发布:编程导论 梁杰 pdf 编辑:程序博客网 时间:2024/05/13 18:40
两道题都是inorder traversal, 第二道题目要求如下,可以看出是要in order

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

首先 in order traversal

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> parentStack = new Stack<TreeNode>();
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        while(root!=null||!parentStack.isEmpty()){
            while(root!=null){
                parentStack.push(root);
                root=root.left;
                }
             root = parentStack.pop();
             result.add(root.val);
             root = root.right;
        }
        return result;
    }
}

然后 Binary Search Tree Iterator  

public class BSTIterator {
      Stack<TreeNode> parentstack = new Stack<>();
      TreeNode crt  ;
    public BSTIterator(TreeNode root) {
         crt = root;
    }


    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return (crt!=null || !parentstack.isEmpty());
    }


    /** @return the next smallest number */
    public int next() {
        int result=0;
        while(crt!=null){
            parentstack.push(crt);
            crt=crt.left;
        }
        crt = parentstack.pop();
        result = crt.val;
        crt= crt.right;
        return result;
    }
}

0 0
原创粉丝点击