题目
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;
}
}
}
本文介绍了如何使用递归和非递归方法将二叉树展平为链表,包括了解法1的递归实现和解法2的非递归实现,详细解释了每种方法的原理和步骤。
293

被折叠的 条评论
为什么被折叠?



