LeetCode – Reorder List (Java)

Given a singly linked list L: L0→L1→ … →Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… For example, given {1,2,3,4}, reorder it to {1,4,2,3}. You must do this in-place without altering the nodes’ values. Java Solution Because the problem requires “in-place” operations, we can only change their pointers, not creating a new list. This problem can be solved … Read more

Leetcode – Word Break (Java)

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = “leetcode”, dict = [“leet”, “code”]. Return true because “leetcode” can be segmented as “leet code”. 1. Naive Approach This problem can be solve by … Read more

Leetcode – Same Tree

Two binary trees are considered the same if they have identical structure and nodes have the same value. This problem can be solved by using a simple recursive function. public boolean isSameTree(TreeNode p, TreeNode q) { if(p==null && q==null){ return true; }else if(p==null || q==null){ return false; }   if(p.val==q.val){ return isSameTree(p.left, q.left) && isSameTree(p.right, … Read more