题目链接
https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
描述
给定一个二叉树,原地将它展开为一个单链表。
示例
给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
初始代码模板
/**
* 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) {
}
}
代码
/**
* 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) {
if (root == null) {
return;
}
//先把左右两个子树拉平
flatten(root.left);
flatten(root.right);
TreeNode left = root.left;
TreeNode right = root.right;
//左子树置为null,把左子树放在右子树
root.left = null;
root.right = left;
//将原来的右子树接到现在的右子树上
TreeNode p = root;
while (p.right != null) {
p = p.right;
}
p.right = right;
}
}
本文介绍了一种算法,用于将二叉树原地转换成单链表,并提供了详细的实现步骤与示例。通过该算法,可以有效地改变二叉树的结构,使其成为一种特殊形式的链表。
298

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



