Flatten Binary Tree to Linked List - Ryan的修炼之路
Given a binary tree, flatten it to a linked list in-place.For example,Given 1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5\ 6
递归法
思路
相当于一次先序遍历, 将先访问的点存储在数组里, 下一个访问的节点为之前访问的点的右子树
复杂度
时间O(n)。空间上是栈的大小,O(logn)
代码
public void flatten(TreeNode root) { if (root == null) { return; } TreeNode[] list = new TreeNode[1]; helper(list, root);}public void helper(TreeNode[] list, TreeNode root) { if (root == null) { return; } TreeNode right = root.right; if (list[0] != null) { list[0].right = root; list[0].left = null; } list[0] = root; helper(list, root.left); helper(list, right);}
非递归解法
思路
对于一个节点我们把右子树入栈, 左子树放在右边. 如果左子树没有了我们就把栈内最近的节点拿出来作为节点的右子树
复杂度
时间O(n) 空间O(n)
代码
public void flatten(TreeNode root) { if (root == null) { return; } Stack<TreeNode> stack = new Stack<TreeNode>(); while (root != null || !stack.isEmpty()) { if (root.right != null) {stack.push(root.right); } if (root.left != null) {root.right = root.left;root.left = null; } else if (!stack.isEmpty()) {TreeNode node = stack.pop();root.right = node; } root = root.right; }}