题目:
给你二叉树的根结点 root
,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用
TreeNode
,其中right
子指针指向链表中下一个结点,而左子指针始终为null
。 - 展开后的单链表应该与二叉树 先序遍历 顺序相同。
方法一:先前序遍历,然后再修改左右指针
class Solution {
public void flatten(TreeNode root) {
List<TreeNode> list = new ArrayList<TreeNode>();
preorderTraversal(root, list);
int size = list.size();
for(int i = 1; i < size; i++) {
TreeNode pre = list.get(i - 1), cur = list.get(i);
pre.right = cur;
pre.left = null;
}
}
private void preorderTraversal(TreeNode root, List<TreeNode> list) {
if (root == null)
return;
list.add(root);
preorderTraversal(root.left, list);
preorderTraversal(root.right, list);
}
}
方法二:寻找前驱节点
class Solution {
public void flatten(TreeNode root) {
TreeNode curr = root;
while (curr != null) {
if (curr.left != null) {
TreeNode next = curr.left;
TreeNode predecessor = next;
while (predecessor.right != null) {
predecessor = predecessor.right;
}
predecessor.right = curr.right;
curr.left = null;
curr.right = next;
}
curr = curr.right;
}
}
}