Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.


Two Stack

    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> pred = new Stack<>(), succ = new Stack<>();
        initStack(pred, succ, root, target);
        while(k-- > 0){
            if(succ.isEmpty() || !pred.isEmpty() && target - pred.peek().val < succ.peek().val - target){
                list.add(pred.peek().val);
                getPredecessor(pred);
            }
            else{//Since N > k, always have something to add
                list.add(succ.peek().val);
                getSuccessor(succ);
            }
        }
        return list;
    }

    // find closet elements until Null.
    // the elements in the top of two stacks must be the predecessor and successor of target value.
    private void initStack(Stack<TreeNode> pred, Stack<TreeNode> succ, TreeNode root, double target){
        while(root != null){
            if(root.val <= target){
                pred.push(root);
                root = root.right;
            }
            else{
                succ.push(root);
                root = root.left;
            }
        }
    }

    // put all node on path into predecessor stack
    private void getPredecessor(Stack<TreeNode> st){
        TreeNode node = st.pop();
        if(node.left != null){
            st.push(node.left);
            while(st.peek().right != null)  st.push(st.peek().right);
        }
    }

    // put all node on path into successor stack
    private void getSuccessor(Stack<TreeNode> st){
        TreeNode node = st.pop();
        if(node.right != null){
            st.push(node.right);
            while(st.peek().left != null)   st.push(st.peek().left);
        }
    }

results matching ""

    No results matching ""