/**
* 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<>();
preOrder(root,list);
for (int i = 0; i < list.size() - 1; i++) {
TreeNode pre = list.get(i), curr = list.get(i + 1);
pre.left = null;
pre.right = curr;
}
}
private void preOrder(TreeNode root, List<TreeNode> list) {
if(root != null){
list.add(root);
preOrder(root.left,list);
preOrder(root.right,list);
}
}
}
114. 二叉树展开为链表
于 2023-07-01 15:52:00 首次发布
该代码片段展示了一个Java类Solution,它包含两个方法:flatten和preOrder。flatten方法通过前序遍历将给定的二叉树扁平化,将所有节点链接成单链结构,而preOrder方法用于辅助进行前序遍历。
摘要由CSDN通过智能技术生成