二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
二叉樹(shù)的層序遍歷算法 + 打印二叉樹(shù)所有最左邊的元素(算法)
層序遍歷
/** * 樹(shù)結(jié)構(gòu)定義 */ private static class BinaryNode<T> {BinaryNode(T theElement) {this(theElement, null, null);}BinaryNode(T theElement, BinaryNode<T> lt, BinaryNode<T> rt) {element = theElement;left = lt;right = rt;}T element;BinaryNode<T> left;BinaryNode<T> right; }//層序遍歷方法 public static void levelRead(BinaryNode node) {if (node == null) {return;}//計(jì)算深度int depth = calcDepth(node);for (int i = 0; i < depth; i++) {//打印每個(gè)深度上的所有節(jié)點(diǎn)readLevel(node,i);}}private static void readLevel(BinaryNode node, int i) {if (node == null||i<1) {return;}//遞歸打印,如果層級(jí)為1,則打印當(dāng)前節(jié)點(diǎn),如果不為1,則說(shuō)明還在比較高的等級(jí),需要遞歸從頭往下繼續(xù)找當(dāng)前層。if (i == 1) {System.out.print(node.element+" ");}readLevel(node.left, i-1);readLevel(node.right, i-1);}private static int calcDepth(BinaryNode node) {if (node ==null) {return 0;}int ld = calcDepth(node.left);int rd = calcDepth(node.right);if (ld>rd) {return ld+1;}else{return rd+1;} }打印二叉樹(shù)所有最左邊的元素
在層序遍歷的基礎(chǔ)上,我們可以借此實(shí)現(xiàn)打印二叉樹(shù)上所有最左邊的元素,代碼如下:
public static void levelReadLeft(BinaryNode node) {if (node == null) {return;}int depth = calcDepth(node);for (int i = 1; i <= depth; i++) {String string = readLevelLeft(node,i);System.out.println(string);} }private static String readLevelLeft(BinaryNode node, int i) {String reString = "";if (node == null||i<1) {return reString;}if (i == 1) {return reString + (node.element+" ");}reString += readLevelLeft(node.left, i-1);if (reString.equals ("")) {reString += readLevelLeft(node.right, i-1);}return reString; }private static int calcDepth(BinaryNode node) {if (node ==null) {return 0;}int ld = calcDepth(node.left);int rd = calcDepth(node.right);if (ld>rd) {return ld+1;}else{return rd+1;} }從頂層遍歷最右邊節(jié)點(diǎn)
代碼如下:
public static void levelReadRight(BinaryNode node) {if (node == null) {return;}int depth = calcDepth(node);for (int i = 1; i <= depth; i++) {String string = readLevelRight(node,i);System.out.println(string);} }private static String readLevelRight(BinaryNode node, int i) {String reString = "";if (node == null||i<1) {return reString;}if (i == 1) {return reString + (node.element+" ");}reString += readLevelRight(node.right, i-1);if (reString.equals ("")) {reString += readLevelRight(node.left, i-1);}return reString; }private static int calcDepth(BinaryNode node) {if (node ==null) {return 0;}int ld = calcDepth(node.left);int rd = calcDepth(node.right);if (ld>rd) {return ld+1;}else{return rd+1;} }總結(jié)
以上是生活随笔為你收集整理的二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 快排算法的Java实现
- 下一篇: git中统计代码提交数