LeetCode 114. Flatten Binary Tree to Linked List
Problem Description:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
题解:
这个题我首先想到的是前序遍历。直接采用前序遍历会因为遍历的同时修改造成错误,需要提前记录下左右子树的引用。代码如下
TreeNode head, tail; public void flatten(TreeNode root) { head = null; tail = null; dfs(root); } private void dfs(TreeNode root) { if(root == null) return; // System.out.println(root.val); TreeNode right = root.right; TreeNode left = root.left; if(head == null) { head = tail = root; } else { tail.right = root; tail.left = null; tail = root; } dfs(left); dfs(right); }
看到讨论区有后序遍历的方法,感觉更加精简:
private TreeNode prev = null; public void flatten(TreeNode root) { if (root == null) return; flatten(root.right); flatten(root.left); root.right = prev; root.left = null; prev = root; }