public static void flattenIterative1(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); while (root != null) { if (root.left != null) { stack.push(root); root = root.left; } else if (root.right != null) { stack.push(root); root = root.right; } else if (!stack.isEmpty()) { TreeNode end = root; while (!stack.isEmpty() && (stack.peek().left == null || (stack.peek().left != null && stack.peek().left != root))) { root = stack.pop(); } if (stack.isEmpty()) root = root.right; else { TreeNode top = stack.peek(); TreeNode temp = top.right; top.right = root; top.left = null; end.right = temp; root = (end.left != null || temp == null) ? end : temp; } } else root = root.right; } }
public static void flatten1(TreeNode root) { while (root != null) { if (root.left != null) flatten1(root.left); TreeNode temp = root.right; root.right = root.left; root.left = null; while (root.right != null) root = root.right; root.right = temp; root = root.right; } }
public static void flatten(TreeNode root) { if (root == null) return; flatten(root.right); flatten(root.left); root.right = prev; root.left = null; prev = root; }
public static void flattenIterative(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode treeNode = stack.pop(); if (treeNode.right != null) stack.push(treeNode.right); if (treeNode.left != null) stack.push(treeNode.left); if (!stack.isEmpty()) treeNode.right = stack.peek(); treeNode.left = null; } }