NOTE
Flatten Binary Tree to Linked List
Flatten a binary tree in place into a linked list whose node order follows the tree's preorder traversal.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given the root root of a binary tree, flatten it into a singly linked list:
The flattened list should still use TreeNode, where the right pointer points to the next node and the left pointer is always null.
The flattened list should follow the same order as the binary tree’s preorder traversal.
2. Approach
- Approach 1
- Save the preorder traversal into an array
- Modify the previous and next pointers of each element in the array
- Approach 2
- Postorder traversal
- Approach 3
- Keep the previous node while doing preorder traversal
3. Implementation
3.1. Approach 1
package main
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
if root == nil {
return
}
res := make([]*TreeNode, 0)
preOrdered(root, &res)
for i := 0; i < len(res)-1; i++ {
res[i].Right = res[i+1]
res[i].Left = nil
}
}
func preOrdered(root *TreeNode, res *[]*TreeNode) {
if root == nil {
return
}
*res = append(*res, root)
preOrdered(root.Left, res)
preOrdered(root.Right, res)
}
3.2. Approach 2
func flatten(root *TreeNode) {
var pre *TreeNode
dfs(root, &pre)
}
func dfs(root *TreeNode, pre **TreeNode) {
if root == nil {
return
}
dfs(root.Right, pre)
dfs(root.Left, pre)
root.Right = *pre
root.Left = nil
*pre = root
}
3.3. Approach 3
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
var pre *TreeNode = &TreeNode{}
dfs(root, &pre)
}
func dfs(root *TreeNode, pre **TreeNode) {
if root == nil {
return
}
left := root.Left
right := root.Right
(*pre).Right = root
(*pre).Left = nil
*pre = root
dfs(left, pre)
dfs(right, pre)
}
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub