Flatten a binary tree to a fake “linked list” in pre-order traversal.
Here we use the right pointer in TreeNode as the next pointer in ListNode.
public class Solution {
private TreeNode lastNode = null;
public void flatten(TreeNode root) {
if (root == null) {
return;
}
if (lastNode != null) {
lastNode.left = null;
lastNode.right = root;
}
lastNode = root;
TreeNode right = root.right;
flatten(root.left);
flatten(right);
}
}
本文介绍了一种将二叉树通过先序遍历的方式展平为类似链表结构的方法。具体实现中,利用二叉树节点的右指针作为链表中的下一个节点指针,左指针置空,确保链表的正确形成。
219

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



