您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“什么是Java順序二叉樹”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“什么是Java順序二叉樹”吧!
從數(shù)據(jù)存儲(chǔ)來看,數(shù)組存儲(chǔ)方式和樹的存儲(chǔ)方式可以相互轉(zhuǎn)換,即數(shù)組可以轉(zhuǎn)換成樹,樹可以轉(zhuǎn)換成數(shù)組。如下圖所示:
順序存儲(chǔ)二叉樹的特點(diǎn):
順序存儲(chǔ)通常只考慮完全二叉樹;
第n個(gè)元素的左子節(jié)點(diǎn)為 2 * n+1;
第n個(gè)元素的右子節(jié)點(diǎn)為 2 * n+2;
第n個(gè)元素的父節(jié)點(diǎn)為 (n-1)/2;
n 表示二叉樹中的第幾個(gè)元素(按0開始編號(hào)如上圖所示);
要求給定一個(gè)數(shù)組{1,2,3,4,5,6,7},要求以二叉樹前序遍歷的方式進(jìn)行遍歷,前序遍歷的結(jié)果應(yīng)當(dāng)為1,2,4,5,3,6,7,
附加完成中序遍歷和后序遍歷。
package com.xie.tree; /** * @author: xiexiaofei * @date: 2020-02-09 20:04 * @description: */ public class ArrBinaryTreeDemo { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7}; ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr); System.out.println("順序存儲(chǔ)二叉樹的前序遍歷數(shù)組"); arrBinaryTree.preOrder(0); System.out.println(); System.out.println("順序存儲(chǔ)二叉樹的中序遍歷數(shù)組"); arrBinaryTree.infixOrder(0); System.out.println(); System.out.println("順序存儲(chǔ)二叉樹的后序遍歷數(shù)組"); arrBinaryTree.postOrder(0); System.out.println(); /** * 順序存儲(chǔ)二叉樹的前序遍歷數(shù)組 * 1 2 4 5 3 6 7 * 順序存儲(chǔ)二叉樹的中序遍歷數(shù)組 * 2 4 5 1 3 6 7 * 順序存儲(chǔ)二叉樹的后序遍歷數(shù)組 * 2 4 5 3 6 7 1 */ } } //實(shí)現(xiàn)順序存儲(chǔ)二叉樹遍歷 class ArrBinaryTree { private int[] arr;//存儲(chǔ)數(shù)據(jù)節(jié)點(diǎn)的數(shù)組 public ArrBinaryTree(int[] arr) { this.arr = arr; } /** * 編寫一個(gè)方法,完成順序存儲(chǔ)二叉樹的前序遍歷。 * * @param index 數(shù)組的下標(biāo) */ public void preOrder(int index) { if (arr == null || arr.length == 0) { System.out.println("數(shù)組為空,不能按照二叉樹的前序遍歷"); } //輸出當(dāng)前的元素 System.out.print(arr[index] + " "); //向左遞歸遍歷 if ((2 * index + 1) < arr.length) { preOrder(2 * index + 1); } //向右遞歸 if ((2 * index + 2) < arr.length) { preOrder(2 * index + 2); } } /** * 編寫一個(gè)方法,完成順序存儲(chǔ)二叉樹的中序遍歷。 * * @param index */ public void infixOrder(int index) { if (arr == null || arr.length == 0) { System.out.println("數(shù)組為空,不能按照二叉樹的前序遍歷"); } //向左遞歸遍歷 if ((2 * index + 1) < arr.length) { preOrder(2 * index + 1); } //輸出當(dāng)前的元素 System.out.print(arr[index] + " "); //向右遞歸 if ((2 * index + 2) < arr.length) { preOrder(2 * index + 2); } } /** * 編寫一個(gè)方法,完成順序存儲(chǔ)二叉樹的后序遍歷。 * * @param index */ public void postOrder(int index) { if (arr == null || arr.length == 0) { System.out.println("數(shù)組為空,不能按照二叉樹的前序遍歷"); } //向左遞歸遍歷 if ((2 * index + 1) < arr.length) { preOrder(2 * index + 1); } //向右遞歸 if ((2 * index + 2) < arr.length) { preOrder(2 * index + 2); } //輸出當(dāng)前的元素 System.out.print(arr[index] + " "); } }
到此,相信大家對(duì)“什么是Java順序二叉樹”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。