[LeetCode] 114. Flatten Binary Tree to Linked List
Given the root of a binary tree, flatten the tree into a “linked list”:
- The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
- The “linked list” should be in the same order as a pre-order traversal of the binary tree.
Example 1:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)?
二叉树展开为链表。
给你二叉树的根结点 root ,请你将它展开为一个单链表:展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路一 - 迭代
这里我给出迭代的做法,会用到 stack。照着例子看来,最后的输出是按照先序遍历的顺序来的。所以用 stack 先右后左地塞入每个节点,但是在弹出的时候需要注意一些细节,在重连 right 指针的时候,先不要把那个对应的右节点从 stack 中 pop 出来,否则就会出错。具体的参见代码注释。
复杂度
时间O(n)
空间O(n) - stack
代码
Java实现
1 |
|
JavaScript实现
1 |
|
思路二 - 也是迭代,无需额外空间
参考这个帖子的解法一。
复杂度
时间O(n)
空间O(n) - stack
代码
Java实现
1 |
|
相关题目
1 |
|