题目
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分析
需要按先序遍历的方式将树展平。用先序遍历的递归和非递归方法都行,解法1使用的递归的方法。
还有种非递归的写法,没有借助栈就实现了按先序遍历顺序展平,在构造过程中,只要树中有多出来的分叉(左子树),就嫁接到根节点和右子树之间,具体参见解法2。
解法1
public class FlattenBinaryTreeToLinkedList {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private TreeNode lastVisit = null;
public void flatten(TreeNode root) {
if (root == null) {
return;
}
TreeNode savedRight = root.right;
if (lastVisit != null) {
lastVisit.left = null;
lastVisit.right = root;
}
lastVisit = root;
flatten(root.left);
flatten(savedRight);
}
}
解法2
public class FlattenBinaryTreeToLinkedList {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public void flatten(TreeNode root) {
while (root != null) {
if (root.left != null) {
TreeNode p = root.left;
while (p.right != null) {
p = p.right;
}
p.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}