问题:
难度:medium
说明:
给出一个二叉树,然后弄成链表形状,其实这道题不怎么好,因为给出的 案例也是很迷惑,也没有说需要怎样的顺序,还有二叉树有序还是无序,排列之后需要有序还是无序。
问题链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
输入案例:
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
我的代码:
因为题目确实很迷惑,他给出的案例有一定顺序的,但是数据里面却无序,我又不可能一点一点试过去,我可能很长时间都会被他那顺序疑惑着。不过具体解法其实就是:把左边的弄到右边来,但是顺序怎么办,看缘分,只有代码对了才对。
class Solution {
public void flatten(TreeNode root) {
if(root != null) recurtion(root);
}
public TreeNode recurtion(TreeNode root) {
if(root.right != null) { // 每次递归进来都对节点右节点进行排序
recurtion(root.right);
}
if(root.left != null) {
TreeNode left = recurtion(root.left); // 左边的节点也是先整理了右边节点的,最后肯定返回一个排好序的左节点
TreeNode last = left;
while(last.right != null) last = last.right;
last.right = root.right;
root.right = left;
root.left = null;
}
return root;
}
}