LeetCode 114. 二叉树展开为链表
题目描述
给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
二叉树展开为链表
提示:
一、解题关键词
二、解题报告
1.思路分析
2.时间复杂度
3.代码示例
/**
* 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 {
TreeNode pre = null;
public void flatten(TreeNode root) {
if(root == null){return;}
flatten(root.right);
flatten(root.left);
root.right = pre;
System.out.println(pre);
root.left = null;
pre = root;
}
}
2.知识点
本文详细介绍了LeetCode第114题的解决方案,即如何将给定的二叉树展开为一个单链表。首先,我们通过先序遍历的方式,对二叉树进行展开。通过递归函数,先处理右子树,再处理左子树,然后将当前节点的右指针指向其前一个节点,左指针置为null。最终得到的链表顺序与二叉树的先序遍历顺序一致。示例代码中展示了具体的实现过程,使用Java的TreeNode类定义了二叉树节点。
697

被折叠的 条评论
为什么被折叠?



