给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private TreeNode[] solve(TreeNode root) {
if (root == null) {
return new TreeNode[2];
}
TreeNode[] left = solve(root.left);
TreeNode[] right = solve(root.right);
TreeNode[] ret = new TreeNode[]{root, root};
if (left[0] != null) {
root.right = left[0];
ret[1] = left[1];
}
if (right[0] != null) {
ret[1].right = right[0];
ret[1] = right[1];
}
ret[0].left = null;
ret[1].right = null;
return ret;
}
public void flatten(TreeNode root) {
if (root == null) {
return;
}
solve(root);
}
}
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;
}
}