LeetCode 272 Closest Binary Tree Traversal II 解題思路

胡椒五菇發表於2019-01-19

原題網址:https://leetcode.com/problems…

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

Note:

Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

Hint:

Consider implement these two helper functions:

getPredecessor(N), which returns the next smaller node to N.
getSuccessor(N), which returns the next larger node to N.

Try to assume that each node has a parent pointer, it makes the problem much easier.

Without parent pointer we just need to keep track of the path from the root to the current node using a stack.

You would need two stacks to track the path in finding predecessor and successor node separately.

題意:在二叉搜尋樹當中找到離target最近的K個數。

解題思路:
由於二叉搜尋數的inorder中序遍歷是有序的,比如例子中的樹,中序遍歷為[1,2,3,4,5]。我們可以利用這一特性,初始化一個雙端佇列Deque,用來存放k個數,然後用遞迴的方式,先走到the most left(也就是例子中的1),不斷的向Deque中加入元素,直到元素裝滿,也就是Deque的size()到k個了,將當前元素與target的距離和佇列頭部與target的距離進行對比,如果當前元素的距離更小,則用Deque的pollFirst()方法將頭部吐出,把當前元素從addLast()加入。

Example:

Input: root = [4,2,5,1,3], target = 3.714286, and k = 2

    4
   / 
  2   5
 / 
1   3

Output: [4,3]

程式碼如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
     *直接在中序遍歷的過程中完成比較,當遍歷到一個節點時,
     如果此時結果陣列不到k個,我們直接將此節點值加入res中,
     如果該節點值和目標值的差值的絕對值小於res的首元素和目標值差值的絕對值,
     說明當前值更靠近目標值,則將首元素刪除,末尾加上當前節點值,
     反之的話說明當前值比res中所有的值都更偏離目標值,
     由於中序遍歷的特性,之後的值會更加的遍歷,所以此時直接返回最終結果即可,
     */
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        Deque<Integer> deque = new ArrayDeque<>();
        inorder(root, target, k, deque);
        List<Integer> res = new ArrayList<>(deque);
        return res;
    }
    private void inorder(TreeNode root, 
                         double target, 
                         int k, 
                         Deque<Integer> deque) {
        if (root == null) return;
        inorder(root.left, target, k, deque);
        if (deque.size() < k) {
            deque.offer(root.val);
        } else if (Math.abs(root.val - target) < Math.abs(deque.peekFirst()-target) ) {
            deque.pollFirst();
            deque.addLast(root.val);
        } 
        inorder(root.right, target, k, deque);
    }
}

還有一種用Stack完成的方式,思路和遞迴相同,但是iterative的寫法,也有必要掌握,必須把控Stack是否為空的情況,當前的node為null,但是stack中仍然有元素,依然需要進行比較。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        Deque<Integer> deque = new ArrayDeque<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if (deque.size() < k) {
                deque.addLast(cur.val);
            } else if (Math.abs(cur.val - target) < Math.abs(deque.peekFirst() - target)) {
                deque.pollFirst();
                deque.addLast(cur.val);
            }
            cur = cur.right;
        }
        List<Integer> res = new ArrayList<>(deque);
        return res;
    }
    
}

相關文章