思路1:迭代法。首先找到根节点的左子树的最右节点mRight,将根节点的右子树root.right接在mRight的右节点上,再把根节点的左子树接回根节点的右子树上,然后判断下一个根节点是否需要"嫁接"。
class Solution {
public void flatten(TreeNode root) {
while(root!=null)
{
//没有左子树,只需要对右子树操作“嫁接”
if(root.left==null)
{
root=root.right;
}
else
{
//存在左子树,找左子树的最右节点
TreeNode mRight=root.left;
while(mRight.right!=null)
{
mRight=mRight.right;
}
//原右子树接过来左子树的最右节点
mRight.right=root.right;
//左子树接回原右子树上
root.right=root.left;
//形成单链,左子树指向空
root.left=null;
//对下一个节点进行同样的操作
root=root.right;
}
}
}
}
时间O(N),空间 O(1)