Yet another Inorder traversal naive solution (Python)


  • 0
    Q

    This is clearly not an optimal solution. But it can be a good starting point in a real interview.

    class Solution(object):
        def closestKValues(self, root, target, k):
            """
            :type root: TreeNode
            :type target: float
            :type k: int
            :rtype: List[int]
            """
            stack = []
            inorder = []
            while root or stack:
                if root:
                    stack.append(root)
                    root = root.left
                else:
                    root = stack.pop()
                    inorder.append(root.val)
                    root = root.right
            res = sorted(zip(map(lambda x: abs(target - x), inorder),inorder), key=lambda x:x[0])
            return map(lambda x: x[1], res[:k])

  • 0
    L

    public class Solution {
    public boolean containsDuplicate(int[] nums) {
    Arrays.sort(nums);
    for (int i = 0; i < nums.length-1; i++) {
    if(nums[i] == nums[i+1]) return true;
    }
    return false;
    }
    }``


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.