@Test public void test() { int[] A = new int[] {0, 1, 0, 0, 4, 0, 5}; int[] B = new int[] {0, 1, 0, 0, 4, 0, 5}; TreeNode root = new TreeNode(A); TreeNode root2 = new TreeNode(B); System.out.println(root.printTree()); System.out.println(sinkZerosInBT(root).printTree()); System.out.println(sinkZerosInBT2(root2).printTree()); }
/* * Recursion. Sink zeros in child subtree first, and then parent. * time: O(n^2); space: O(1) */ public TreeNode sinkZerosInBT(TreeNode root) { if (root == null) return null; root.left = sinkZerosInBT(root.left); root.right = sinkZerosInBT(root.right); if (root.val == 0) { TreeNode node = getLowestNonZeroNode(root); swap(root, node); } return root; }
private void swap(TreeNode root, TreeNode node) { int tmp = root.val; root.val = node.val; node.val = tmp; }