114. Flatten Binary Tree to Linked List
Question
Given the
root
of a binary tree, flatten the tree into a “linked list”:
- The “linked list” should use the same
TreeNode
class where theright
child pointer points to the next node in the list and theleft
child pointer is alwaysnull
.- The “linked list” should be in the same order as a pre-order** traversal** of the binary tree.
Solution
全局变量prev,初始化为null,用来记录上一个访问的节点。
由于最后要达到先序遍历(根节点-左子节点-右子节点)的数据结构顺序,因此在进行访问时需要与先序遍历的操作相反,首先递归右子节点,然后递归左子节点,最后修改当前节点。
先遍历当前节点的右侧节点,再遍历当前节点的左侧节点。
最后处理当前节点,将左子节点设置为null,右子节点设置为prev。
最后将当前节点保存在prev上。
Code
1 | /** |
114. Flatten Binary Tree to Linked List
https://xuanhe95.github.io/2022/07/27/114-Flatten-Binary-Tree-to-Linked-List/