Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / 2 5 / 3 4 6 The flattened tree should look like: 1 2 3 4 5 6 click to show hints. Hints: If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
第二遍做法:不用ArrayList来wrap up previous node, 直接把previous node做成全局变量
1 public class Solution { 2 TreeNode pre = null; 3 4 public void flatten(TreeNode root) { 5 if (root == null) return; 6 helper(root); 7 } 8 9 public void helper(TreeNode cur) { 10 if (pre != null) { 11 pre.left = null; 12 pre.right = cur; 13 } 14 pre = cur; 15 TreeNode left = cur.left; 16 TreeNode right = cur.right; 17 if (left != null) helper(left); 18 if (right != null) helper(right); 19 } 20 }
第一遍做法:用递归来解决,维护先序遍历的前一个结点pre,然后每次把pre的左结点置空,右结点设为当前结点。这里需要注意的一个问题就是我们要先把左右子结点(Code Ganker说只需要右节点,我是保存了左右节点)保存一下,以便等会可以进行递归,否则有可能当前结点的右结点会被覆盖,后面就取不到了。算法的复杂度时间上还是一次遍历,O(n)。空间上是栈的大小,O(logn)。
1 public class Solution { 2 public void flatten(TreeNode root) { 3 ArrayList<TreeNode> pre = new ArrayList<TreeNode>(); 4 pre.add(root); 5 helper(root, pre); 6 } 7 8 public void helper(TreeNode root, ArrayList<TreeNode> pre) { 9 if (root == null) return; 10 TreeNode left = root.left; 11 TreeNode right = root.right; 12 if (root != pre.get(0)) { 13 TreeNode parent = pre.get(0); 14 parent.left = null; 15 parent.right = root; 16 pre.set(0, root); 17 } 18 helper(left, pre); 19 helper(right, pre); 20 } 21 }
Iterative: 与平时写Preorder的iterative不大一样
1 public class Solution { 2 public void flatten(TreeNode root) { 3 if (root == null) return; 4 TreeNode pre = null; 5 Stack<TreeNode> st = new Stack<TreeNode>(); 6 TreeNode cur = root; 7 st.push(cur); 8 while (!st.isEmpty()) { 9 cur = st.pop(); 10 if (pre != null) { 11 pre.left = null; 12 pre.right = cur; 13 } 14 pre = cur; 15 if (cur.right != null) st.push(cur.right); 16 if (cur.left != null) st.push(cur.left); 17 } 18 } 19 }