题目
题解
前序遍历
根据前序遍历序更改树结点的指针指向
class Solution {
List<TreeNode>list=new ArrayList<>();
public void flatten(TreeNode root) {
if(root==null)
return;
preOrder(root);//获得树的前序遍历序,存入list中
for(int i=1;i<list.size();i++){
TreeNode pre=list.get(i-1),cur=list.get(i);
pre.right=cur;//结点放在右子
pre.left=null;
}
}
//获得前序遍历序
public void preOrder(TreeNode root){
if(root!=null){
list.add(root);
preOrder(root.left);
preOrder(root.right);
}
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)
寻找前驱结点
前序遍历的顺序是:根 左 右,
- 如果一个结点的左子空,无需展开
- 如果一个结点的左子不空,左子树访问完后,访问右子树;左子树最后访问的是最右结点,即右子树的前驱结点
因此,问题转化成寻找当前节点的前驱节点。
我们需要两步完成这道题。
- 将原来的右子树接到左子树的最右边节点(即他的前驱结点)
- 将左子树插入到右子树的地方
- 考虑新的右子树的根节点,一直重复上边的过程,直到新的右子树为 null
class Solution {
List<TreeNode>list=new ArrayList<>();
public void flatten(TreeNode root) {
while(root!=null){
//左子不空
if(root.left!=null){
TreeNode pre=root.left;
while(pre.right!=null){
pre=pre.right;
}
//右子树接到左子最右(前驱)
pre.right=root.right;
//左子树插入到右子树的地方
root.right=root.left;
root.left=null;
}
//考虑下一个结点
root=root.right;
}
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1),优于第一种方法