给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
思路与代码
前序遍历
把节点按前序遍历的顺序取出,方法一个数组或者队列里,再依次建立新的连接
时间复杂度O(n)
空间复杂度O(n)
需要额外的数组或队列
class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList();
pre_order(root, queue);
TreeNode preNode = queue.poll();
while (!queue.isEmpty()) {
TreeNode curNode = queue.poll();
preNode.left = null;
preNode.right = curNode;
preNode = curNode;
}
}
public void pre_order(TreeNode root, Queue<TreeNode> queue) {
if (root == null) return;
queue.offer(root);
pre_order(root.left, queue);
pre_order(root.right, queue);
}
}
建立前驱节点
我们在上面一种方法中为什么要用额外的数组来存取呢,是因为如果在前序遍历中,我们直接root.right = root.left
,那么就是破坏掉了树的结构,我们还没有遍历过右节点,就已经无法找到它了。
现在我们这样做:
对于每一个root节点,找到其左子树的最右节点作为pre节点,使其指向root节点的右子树,而此时我们已经为右节点找好了pre节点,所以可以直接root.right = root.left
,之前的右子树仍然没有与整棵树断开联系。过程如下图:
1
/ \
2 5
/ \ \
3 4 6
1
\
2
/ \
3 4
\
5
\
6
1
\
2
\
3
\
4
\
5
\
6
class Solution {
public void flatten(TreeNode root) {
while(root != null) {
if (root.left != null) {
// 左子树的最右节点作为pre节点,使其指向root节点的右子节点
TreeNode pre = root.left;
while(pre.right != null) pre = pre.right;
pre.right = root.right;
// 调整当前root节点
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}