题目链接
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;
}
}