📅  最后修改于: 2023-12-03 15:09:33.975000             🧑  作者: Mango
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
展开后的单链表应为:
1 -> 2 -> 3 -> 4 -> 5 -> 6
将每个节点的左子树拼接到其右子树的下面。具体的做法是:
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return
self.flatten(root.left)
self.flatten(root.right)
left = root.left
right = root.right
root.left = None
root.right = left
while root.right:
root = root.right
root.right = right
class Solution {
public void flatten(TreeNode root) {
if (root == null) {
return;
}
flatten(root.left);
flatten(root.right);
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
root.right = left;
TreeNode cur = root;
while (cur.right != null) {
cur = cur.right;
}
cur.right = right;
}
}