方法1 硬写
思路: 先将右子树转换成链表。然后将左子树转换成链表。将左子树接到右子树上,左子树最后一个节点的右子树为根节点之前的右子树。
代码
public void flatten(TreeNode root){
if (root==null){
return;
}
TreeNode right=root.right;
flatten(root.right);
flatten(root.left);
if(root.left!=null){
TreeNode p=root.left;
root.right=root.left;
root.left=null;
while(p.right!=null){
p=p.right;
}
p.right=right;
}
}
方法二 找到右子树的前一个节点
找到当前节点curr,curr右子树的最右节点为pre。将curr.right置为pre.right,curr.right=curr.left,curr.left=null.然后对右子树进行递归
public void flatten(TreeNode root) {
TreeNode curr = root;
if (curr == null) {return;}
if (curr.left != null) {
TreeNode next = curr.left;
TreeNode predecessor = next;
while (predecessor.right != null) {
predecessor = predecessor.right;
}
predecessor.right = curr.right;
curr.left = null;
curr.right = next;
}
flatten(curr.right);
}