package com.imdevil.JobInterview;
import java.util.Stack;
public class BtTree{
static class Node{
char data;
Node lchild;
Node rchild;
public Node() {
}
public Node(char data,Node lchild,Node rchild){
this.data = data;
this.lchild = lchild;
this.rchild = rchild;
}
}
public Node createBtTree(String str){
Stack<Node> stack = new Stack<>();
Node bt = null;
Node node = null;
int k = 0;
for(int i=0;i<str.length();i++){
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'z') {
node = new Node();
node.data = str.charAt(i);
node.lchild = null;
node.rchild = null;
if (bt == null) {
bt = node;
}else {
switch (k) {
case 1:
stack.peek().lchild = node;
break;
case 2:
stack.peek().rchild = node;
break;
default:
break;
}
}
}else if(str.charAt(i) == '(') {
stack.push(node);
k = 1;
}else if(str.charAt(i) == ')'){
stack.pop();
}else if (str.charAt(i) == ',') {
k = 2;
}
}
return bt;
}
public int depth(Node bt){
if (bt == null) {
return 0;
}
int left = depth(bt.lchild);
int right = depth(bt.rchild);
return Math.max(left, right)+1;
}
public void preOrder(Node node) {
if (node != null) {
System.out.print(node.data);
preOrder(node.lchild);
preOrder(node.rchild);
}
}
public void midOrder(Node node){
if (node != null) {
midOrder(node.lchild);
System.out.print(node.data);
midOrder(node.rchild);
}
}
public void postOrder(Node node){
if (node != null) {
postOrder(node.lchild);
postOrder(node.rchild);
System.out.print(node.data);
}
}
public void dispLeaf(Node node){
if (node != null) {
if (node.lchild == null && node.rchild == null) {
System.out.print(node.data);
}
dispLeaf(node.lchild);
dispLeaf(node.rchild);
}
}
public static void main(String[] args) {
String str = "A(B(D(,G),)C(E,F))";
BtTree tree = new BtTree();
Node node = tree.createBtTree(str);
System.out.println(tree.depth(node)); --->4
tree.preOrder(node); --->ABDGCEF
System.out.println();
tree.midOrder(node); --->DGBAECF
System.out.println();
tree.postOrder(node); ---->GDBEFCA
System.out.println();
tree.dispLeaf(node); --->GEF
}
}
二叉樹(shù)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- AVL樹(shù),紅黑樹(shù),B樹(shù),B+樹(shù),Trie樹(shù)都分別應(yīng)用在哪些現(xiàn)實(shí)場(chǎng)景中? 參考知乎知友的回答AVL樹(shù),紅黑樹(shù),B樹(shù),...
- BST樹(shù)即二叉搜索樹(shù):1.所有非葉子結(jié)點(diǎn)至多擁有兩個(gè)兒子(Left和Right);2.所有結(jié)點(diǎn)存儲(chǔ)一個(gè)關(guān)鍵字;3....
- 簡(jiǎn)單來(lái)說(shuō), 完全二叉樹(shù)是指按照層次進(jìn)行遍歷的時(shí)候所得到的序列與滿二叉樹(shù)相對(duì)應(yīng) 這里提供兩種思路和相應(yīng)的代碼: 1....
- 思路: 從根節(jié)點(diǎn)開(kāi)始,判斷左右子樹(shù)是否是平衡的,如果都是平衡的,則判斷左右子樹(shù)的高度差是否不大于1 復(fù)雜度: O(n)