118119120121122123124125126127128
return buildTree(index, listMap); } static TreeNode buildTree(int val, Map<Integer, ArrayList<Integer>> listMap) { TreeNode root = new TreeNode(val); ArrayList<Integer> list = listMap.get(val); if (list == null) { return root;
6667686970717273
static ListNode head; public static void main(String[] args) { LinkedList list = new LinkedList(new int[]{1, 2, 3, 4, 5, 6, 7}); head = list.head; TreeNode root = sortedListToBST(7); root.print(); }
242526272829303132
import adt.tree.TreeNode; public class Q068_Deepest_left_leaf_node_in_a_binary_tree { public static void main(String[] args) { TreeNode root = Tree.tree12(); findDeepestLeftLeaf(root, 1, false); System.out.format("%d\n", val); }
75767778798081828384858687
static TreeNode sortedListToBST(int n) { if (n <= 0) { return null; } TreeNode left = sortedListToBST(n/2); TreeNode root = new TreeNode(head.val); root.left = left; head = head.next; // 这个是最巧妙的地方!
3334353637383940414243
import adt.tree.TreeNode; public class Q050_Floor_and_Ceil_from_a_BST { public static void main(String[] args) { TreeNode root = Tree.bst2(); int ceil = findCeil(root, 17); System.out.format("ceil: %d\n", ceil); int floor = findFloor(root, 17);
2829303132333435363738
import adt.tree.TreeNode; public class Q003_Determine_if_Two_Trees_are_Identical { public static void main(String[] args) { TreeNode r1 = Tree.tree1(); TreeNode r2 = Tree.bst1(); boolean res = isIdentical(r1, r2); System.out.println(res); }
484950515253545556
import adt.tree.TreeNode; public class Q041B_Merge_two_BSTs_with_limited_extra_space { public static void main(String[] args) { TreeNode r1 = Tree.bst1(); TreeNode r2 = Tree.bst2(); merge(r1, r2); }
686970717273747576777879
} Stack<TreeNode> s1 = new Stack<TreeNode>(); Stack<TreeNode> s2 = new Stack<TreeNode>(); TreeNode curr1 = r1; TreeNode curr2 = r2; // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (!s1.isEmpty() || !s2.isEmpty() || curr1 != null || curr2 != null) {
3839404142434445
public class Q034_Sorted_Array_to_Balanced_BST { public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; TreeNode tree = sortedArrayToBST(arr, 0, arr.length - 1); tree.print(); }
4950515253545556575859
return null; } int mid = lo + (hi - lo) / 2; TreeNode root = new TreeNode(arr[mid]); root.left = sortedArrayToBST(arr, lo, mid - 1); root.right = sortedArrayToBST(arr, mid + 1, hi); return root;