Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
题意:看不懂……弄了几棵树跑结果发现是先序遍历
解决思路:先序遍历
代码:
public class Solution {
public void flatten(TreeNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
return;
}
while (root != null) {
if (root.left == null) {
root = root.right;
continue;
}
TreeNode left = root.left;
while (left.right != null) {
left = left.right;
}
left.right = root.right;
root.right = root.left;
root.left = null;
root = root.right;
}
}
}