資料結構之自平衡二叉尋找樹(2)

來源:互聯網
上載者:User

在上一節我們講述了AVL樹的基本知識,並實現了自平衡二叉尋找樹的插入操作,這一節裡我們來實現一下刪除操作。

刪除操作的Java代碼實現如下所示,其他代碼和前一講相同。

         //刪除一個節點public void remove(int data){rootnode=remove(data,this.rootnode);}private AVLTreeNode remove(int data,AVLTreeNode root){if(root==null){return root;}if(data<root.data){root.left=remove(data,root.left);}else if(data>root.data){root.right=remove(data,root.right);}else if(root.left!=null&&root.right!=null){root.data=minAVLTreeNode(root.right).data;root.right=remove(root.data,root.right);}else{root=root.left!=null?root.left:root.right;}return balance(root);}//擷取以begin為根節點的樹的最小關鍵字節點的引用private AVLTreeNode minAVLTreeNode(AVLTreeNode begin){if(begin==null)return null;while(begin.left!=null){begin=begin.left;}return begin;}

在主程式中我們做如下處理:

                  mytree.insert(4);mytree.insert(3);mytree.insert(2);mytree.insert(1);mytree.insert(5);mytree.remove(4);mytree.remove(5);

運行結果如下所示:

遞迴方式實現前序走訪:2 1 3 遞迴方式實現中序遍曆:1 2 3 遞迴方式實現後序遍曆:1 3 2 非遞迴方式實現前序走訪:2 1 3 非遞迴方式實現中序遍曆:1 2 3 非遞迴方式實現後序遍曆:1 3 2 

從運行結果中我們可以看出,在刪除之後,剩下的1,2,3三個節點已經不滿足平衡條件,同過平衡化處理之後得到一個新的平衡化二叉尋找樹。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.