Leetcode - Closest Binary Search Tree Value II

My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List closestKValues(TreeNode root, double target, int k) {
        Stack st = new Stack();
        Stack pre = new Stack();
        Stack suc = new Stack();
        
        TreeNode p = root;
        while (p != null) {
            st.push(p);
            p = p.left;
        }
        
        while (!st.isEmpty()) {
            p = st.pop();
            if (p.val > target) {
                break;
            }
            pre.push(p);
            if (p.right != null) {
                p = p.right;
                while (p != null) {
                    st.push(p);
                    p = p.left;
                }
            }
        }
        
        st.clear();
        
        p = root;
        while (p != null) {
            st.push(p);
            p = p.right;
        }
        
        while (!st.isEmpty()) {
            p = st.pop();
            if (p.val <= target) {
                break;
            }
            suc.push(p);
            if (p.left != null) {
                p = p.left;
                while (p != null) {
                    st.push(p);
                    p = p.right;
                }
            }
        }
        
        List ret = new ArrayList();
        while (k > 0) {
            if (pre.isEmpty()) {
                ret.add(suc.pop().val);
            }
            else if (suc.isEmpty()) {
                ret.add(pre.pop().val);
            }
            else if (Math.abs(pre.peek().val - target) < Math.abs(suc.peek().val - target)) {
                ret.add(pre.pop().val);
            }
            else {
                ret.add(suc.pop().val);
            }
            k--;
        }
        
        return ret;
    }
}

reference:
https://discuss.leetcode.com/topic/22940/ac-clean-java-solution-using-two-stacks/2

没能自己做出来。看了解析,觉得思路是那么的理所当然,竟然没想出来。。。
他给的答案是recursion
我重写了一个 iteration的方法,都差不多。

一个注意点是,
如果 pre 的break条件是 val > target

那么 suc 的break条件必须是 val <= target
不能是 val < target

否则,会把相同的数字放进两个栈中,造成错误的结果。

以后再给你一个binary search tree,的确可以用这种双栈的办法,实现双指针,从中间往左右扫描。

Anyway, Good luck, Richardo! -- 09/07/2016

你可能感兴趣的:(Leetcode - Closest Binary Search Tree Value II)