题目
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
解题思路:利用递归找到倒数第一个父节点,记录下它的右节点,将左边的移到右边,然后再把之前标记的右节点连接上。
代码
public class Solution {
public void flatten(TreeNode root) {
if(root==null) return;
flatten(root.left);
flatten(root.right);
TreeNode temp=root.right;
if(root.left!=null){
root.right=root.left;
root.left=null;
while(root.right != null){
root=root.right;
}
root.right=temp;
}
}
}
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/