1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
public class FlattenBinaryTreeToLinkedList { public void flatten(TreeNode root) { if (root == null) { return; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cursor = new TreeNode(0); stack.push(root); while (!stack.isEmpty()) { cursor.right = stack.pop(); cursor.left = null; cursor = cursor.right; if (cursor.right != null) { stack.push(cursor.right); } if (cursor.left != null) { cursor.right = cursor.left; if (cursor.left.right != null) { stack.push(cursor.left.right); } if (cursor.left.left != null) { stack.push(cursor.left.left); } cursor.left = null; cursor = cursor.right; } } } @Test public void test() { TreeNode root = new TreeNode(1); root.left = new TreeNode(2);
flatten(root); } }
|