leetcode114. flatten binary tree to linked list

将二叉树转化为链表。

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

1
2
3
4
5
    1
/
2 5
/
3 4 6

The flattened tree should look like:

1
2
3
4
5
6
7
8
9
10
11
1

2

3

4

5

6

Hints:

If you notice carefully in the flattened tree, each node’s right child points to the next node of a pre-order traversal.

算法:利用二叉树前序遍历算法的递归实现求解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public TreeNode preNode = null;
public void (TreeNode root) {
if (root == null) return;
if (preNode != null) {
preNode.left = null;
preNode.right = root;
}
preNode = root;

//所以要将当前节点的右子节点存储下来,对右子节点递归时用
TreeNode right = root.right;
flatten(root.left);
flatten(right);
}