二叉搜索树与双向链表

题目:

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

思路:

1、需要选择遍历方法,选择中序遍历可以实现顺序的排列
2、 定义方法ConvertSub(TreeNode pRootOfTree)
3、 先遍历根结点的左子树,在遍历根的右子树;拿到的两个结点相互指向;
4、 定义函数Convert(TreeNode pRootOfTree) ,调用方法ConvertSub(TreeNode pRootOfTree),定义双向链表的头结点;并且函数执行完以后返回头结点;


代码实现:

 class TreeNode {
     
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}


public class Main {
     

   static   TreeNode head = null;
   static TreeNode realHead = null;
    public static void main(String[] args) {
     

        //创建一个二叉搜索树;
        TreeNode a = new TreeNode(10);
        TreeNode a1 = new TreeNode(6);
        TreeNode a2 = new TreeNode(14);
        TreeNode a3 = new TreeNode(4);
        TreeNode a4 = new TreeNode(8);
        TreeNode a5 = new TreeNode(12);
        TreeNode a6 = new TreeNode(16);
        a.left = a1;a.right=a2;a1.left = a3;a1.right=a4;a2.left=a5;a2.right=a6;
        TreeNode head =   Convert(a);
        while (head!=null){
     
            System.out.print(head.val+" ");
        }


    }

    //直接用中序遍历


        public static TreeNode Convert(TreeNode pRootOfTree) {
     
            ConvertSub(pRootOfTree);
            return realHead;
        }

        private static  void ConvertSub(TreeNode pRootOfTree) {
     
            if(pRootOfTree==null) return;
            ConvertSub(pRootOfTree.left);
            if (head == null) {
     
                head = pRootOfTree;
                realHead = pRootOfTree;
            } else {
     
                head.right = pRootOfTree;
                pRootOfTree.left = head;
                head = pRootOfTree;
            }
            ConvertSub(pRootOfTree.right);
        }
}

运行截图:

二叉搜索树与双向链表_第1张图片

你可能感兴趣的:(剑指offer,Java实现,数据结构)