二叉树与链表之间的转换

目录

一、二叉树与双链表之间的转换

(1、解法一

(2、解法二

二、二叉树与单链表之间的转换 

 (1、解法一、前序遍历

(2、解法二、后序遍历


一、二叉树与双链表之间的转换

 牛客网链接:转换问题。

 二叉树与链表之间的转换_第1张图片

 对于这种链表转换的题目,都是要通过遍历来解决问题。

(1、解法一

我们可以专门定义一个函数来将双链表来进行转换,转换完成之后我们,转换完成之后我们找它的头节点就行了。

public class Solution {
    TreeNode cur=null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree==null) return null;
        convertTree(pRootOfTree);
        
        TreeNode temp=pRootOfTree;
        while(temp.left!=null){
            temp=temp.left;
        }
        return temp;
    }
    public void convertTree(TreeNode pCur){
        if(pCur==null) return;
        convertTree(pCur.left);
        
        pCur.left=cur;
        if(cur!=null){
            cur.right=pCur;
        }
        cur=pCur;
        
        convertTree(pCur.right);
    }
}

(2、解法二

我们可以直接在本函数中进行遍历,我们定义两个变量,在函数内部进行定义。

public class Solution {
    TreeNode cur=null;
    TreeNode pre=null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree==null) return null;
        
        Convert(pRootOfTree.left);
        
        if(cur==null){
            cur=pRootOfTree;
        }
        if(pre!=null){
            pRootOfTree.left=pre;
            pre.right=pRootOfTree;
        }
        pre=pRootOfTree;
        
        Convert(pRootOfTree.right);
        
        return cur;
    }
}

二、二叉树与单链表之间的转换 

力扣链接:题目。

二叉树与链表之间的转换_第2张图片

 (1、解法一、前序遍历

class Solution {
    public void flatten(TreeNode root) {
        if(root==null) return;
        if(root.left!=null){
            TreeNode temp=root.left;
            while(temp.right!=null){
                temp=temp.right;
            }
            temp.right=root.right;
            root.right=root.left;
            root.left=null;
        }

        flatten(root.left);

        flatten(root.right);
    }
}

二叉树与链表之间的转换_第3张图片

 对于前序遍历的方法,我们判断根节点的左子树是否为空,通过将右子树接到左子树的右结点上,再将左子树接到右子树上,把左子树置为空。用递归不断的遍历去做就行了。

(2、解法二、后序遍历

class Solution {
    public void flatten(TreeNode root) {
        if(root==null) return;
        flatten(root.left);
        flatten(root.right);

        TreeNode temp=root.right;
        root.right=root.left;
        root.left=null;

        while(root.right!=null){
            root=root.right;
        }
        root.right=temp;
    }
}

二叉树与链表之间的转换_第4张图片

 我们通过后续遍历一步步还原,将右子树取出,将左子树转换成右子树,在将原来的右子树接入。不断的还原就行了。

你可能感兴趣的:(笔记,数据结构,链表,数据结构,算法)