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;
TreeNode left = root.left;
TreeNode right = root.right;
if(left!=null){
flatten(root.left);
root.right = left;
root.left = null;
TreeNode cur = root.right;
while(cur.right!=null)
cur = cur.right;
cur.right = right;
}
if(right!=null)
flatten(right);
}
}