美文网首页
LeetCode 173 Binary Search Tree

LeetCode 173 Binary Search Tree

作者: ShuiLocked | 来源:发表于2016-08-29 19:59 被阅读126次

    LeetCode 173 Binary Search Tree Iterator

    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.

    要求next()具有O(1)的时间复杂度,那必然需要有存储某些节点,能够直接搜索出下一个最小值。根据bst的性质不难发现,最好是存储右子树中最靠左的叶子结点!!!

    我考虑的是用stack,每次记录整条path,直到最靠左的叶子结点,每当next时pop栈顶的结点,同时将右子树中到最靠左叶子结点的path再全部压进栈。

    代码:

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
        
        Stack<TreeNode> st = new Stack<TreeNode>();
        
        public BSTIterator(TreeNode root) {
            while (root != null) {
                st.push(root);
                root = root.left;
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            // System.out.println(st.size());
            if (!st.isEmpty())   return true;
            else return false;
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode curr = st.pop();
            int val = curr.val;
            if (curr.right != null) {
                curr = curr.right;
                st.push(curr);
                // Push the left child of curr.right into stack
                while (curr.left != null) {
                    st.push(curr.left);
                    curr = curr.left;
                }
            }
            return val;
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */
    
    

    相关文章

      网友评论

          本文标题:LeetCode 173 Binary Search Tree

          本文链接:https://www.haomeiwen.com/subject/enffettx.html