日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)

發布時間:2024/9/30 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

二叉樹的層序遍歷算法 + 打印二叉樹所有最左邊的元素(算法)

層序遍歷

/** * 樹結構定義 */ 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++) {//打印每個深度上的所有節點readLevel(node,i);}}private static void readLevel(BinaryNode node, int i) {if (node == null||i<1) {return;}//遞歸打印,如果層級為1,則打印當前節點,如果不為1,則說明還在比較高的等級,需要遞歸從頭往下繼續找當前層。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;} }

打印二叉樹所有最左邊的元素

在層序遍歷的基礎上,我們可以借此實現打印二叉樹上所有最左邊的元素,代碼如下:

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;} }

從頂層遍歷最右邊節點

代碼如下:

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;} }

總結

以上是生活随笔為你收集整理的二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。