二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
二叉樹的層序遍歷算法 + 打印二叉樹所有最左邊的元素(算法)
層序遍歷
/** * 樹結(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;}//計算深度int depth = calcDepth(node);for (int i = 0; i < depth; i++) {//打印每個深度上的所有節(jié)點readLevel(node,i);}}private static void readLevel(BinaryNode node, int i) {if (node == null||i<1) {return;}//遞歸打印,如果層級為1,則打印當前節(jié)點,如果不為1,則說明還在比較高的等級,需要遞歸從頭往下繼續(xù)找當前層。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;} }打印二叉樹所有最左邊的元素
在層序遍歷的基礎上,我們可以借此實現(xiàn)打印二叉樹上所有最左邊的元素,代碼如下:
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é)點
代碼如下:
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é)
以上是生活随笔為你收集整理的二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快排算法的Java实现
- 下一篇: git中统计代码提交数