Problem
Analysis Process
After the binary tree is expanded into a single linked list, the order of nodes in the single linked list is the order of nodes traversed and visited before the binary tree.Therefore, the binary tree can be preordered traversal to get the order of each node to be accessed.Since expanding the binary tree to a linked list will destroy the structure of the binary tree, the information of the left and right children of each node will be updated after the end of the preceding traversal, and the binary tree will be expanded to a single linked list.
Code
golang
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
//Preorder traversal of binary tree by recursion
//The traversed tree is re-encapsulated into a linked list, so that left= NULL and right= the next node of the current node for each node
list := preorderTraversal(root)
for i := 1; i < len(list); i++ {
prev, curr := list[i-1], list[i]
prev.Left, prev.Right = nil, curr
}
}
//Recursive preorder traversal
func preorderTraversal(root *TreeNode) []*TreeNode {
list := []*TreeNode{}
if root != nil {
list = append(list, root)
list = append(list, preorderTraversal(root.Left)...)
list = append(list, preorderTraversal(root.Right)...)
}
return list
}
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
List<TreeNode> list = new ArrayList<TreeNode>();
//Preorder traversal of binary tree by recursion
preorderTraversal(root, list);
//The traversed tree is re-encapsulated into a linked list, so that left= NULL and right= the next node of the current node for each node
int size = list.size();
for (int i = 1; i < size; i++) {
TreeNode prev = list.get(i - 1), curr = list.get(i);
prev.left = null;
prev.right = curr;
}
}
//Recursive preorder traversal
public void preorderTraversal(TreeNode root, List<TreeNode> list) {
if (root != null) {
list.add(root);
preorderTraversal(root.left, list);
preorderTraversal(root.right, list);
}
}
}