二叉搜索樹與雙向鏈表

問題

輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能創建任何新的結點,只能調整樹中結點指針的指向

思考

在這裏插入圖片描述

  • 二叉搜索樹的中序遍歷就是 正常的順序 輸出,因此可以採用中序遍歷 的方式
  • 在遍歷的過程中,要對每個節點進行操作,確定每個節點的前向節點與後向節點,這時可以設置中間值進行保存

代碼


package DlinkedList;

import sun.dc.pr.PRError;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/3/22 0022  16:15
 * 輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。
 * 要求不能創建任何新的結點,只能調整樹中結點指針的指向。
 */
public class Problem13 {


    TreeNode head = null;
    //left  爲上一個值   小於它
    //righjt 爲下一個值 大於它
    //中間值
    TreeNode temp = null;
    TreeNode previous = null;

    public TreeNode Convert(TreeNode pRootOfTree) {

        //若爲空則返回
        if(pRootOfTree==null){return head;}

        //中序遍歷
        if(pRootOfTree.left!=null)
            //注意這裏加return以後這之後的代碼都不會執行
            //因此不能加return
            Convert(pRootOfTree.left);

        
        //當連目標爲空時,即當待返回的鏈表爲空時
        if(head==null){
            head=pRootOfTree;
            temp=head;
            previous=head;
        }else{
        //在這裏需要對每個節點進行處理
            //設置鏈表的尾部元素怒
            temp.right=pRootOfTree;

            //設置鏈表的前一各節點
            pRootOfTree.left=previous;

            //設置尾部節點
            temp=pRootOfTree;

            //更新當前節點爲前一個節點
            previous=temp;


        }

        //右子樹不爲空
        if(pRootOfTree.right!=null)
            Convert(pRootOfTree.right);

        return head;
    }

    public static void main(String[] args) {

       TreeNode A = new TreeNode(5);
       TreeNode B = new TreeNode(3);
       TreeNode C = new TreeNode(7);
       TreeNode D = new TreeNode(2);
       TreeNode E= new TreeNode(4);
       TreeNode F = new TreeNode(6);
       TreeNode G = new TreeNode(8);
       TreeNode H= new TreeNode(9);

       A.left=B;
       A.right=C;
       B.left=D;
       B.right=E;
       C.left=F;
       C.right=G;
       G.right=H;

       Problem13 problem13 = new Problem13();
        TreeNode head = problem13.Convert(A);
//        System.out.println(head.val);
        head.list();




    }


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章