剑指offer-----二叉搜索树与双向链表

一、题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

二、思路

中序遍历树,并时时更新最后一个节点。

根据这三个节点的关系,判断出全局关系,从而写出代码。

三、代码实现

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;


    public TreeNode(int val) {
        this.val = val;


    }


}
*/
public class Solution {
     TreeNode lastNodeInList = null;
      
    public  TreeNode ConvertNode(TreeNode node,TreeNode lastNodeInList){
        if(node == null){
            return null;
            
        }
        TreeNode current = node;
        if(current.left != null){
            lastNodeInList = ConvertNode(current.left,lastNodeInList);
        }
        current.left = lastNodeInList;
        if(lastNodeInList != null){
            lastNodeInList.right = current;
        }
        lastNodeInList = current;
       // System.out.println(lastNodeInList.val);
       
        if(current.right != null){
            lastNodeInList = ConvertNode(current.right,lastNodeInList);//对于递归,必须要接一下返回的参数
            
        }
        return lastNodeInList;
        
    }
    public  TreeNode Convert(TreeNode pRootOfTree) {
           
        
         lastNodeInList = ConvertNode (pRootOfTree,lastNodeInList);
         /*if(lastNodeInList == null) {
        System.out.println("nihao");
         }*/
         
         TreeNode pHeadOfList = lastNodeInList;
         
         while(pHeadOfList!=null && pHeadOfList.left!=null){
        // System.out.println("nihoa");
             pHeadOfList = pHeadOfList.left;
         }
        return pHeadOfList;
        
    }
    
    

}


猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/80169492