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
}
}
二叉樹
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- AVL樹,紅黑樹,B樹,B+樹,Trie樹都分別應用在哪些現實場景中? 參考知乎知友的回答AVL樹,紅黑樹,B樹,...
- BST樹即二叉搜索樹:1.所有非葉子結點至多擁有兩個兒子(Left和Right);2.所有結點存儲一個關鍵字;3....
- 簡單來說, 完全二叉樹是指按照層次進行遍歷的時候所得到的序列與滿二叉樹相對應 這里提供兩種思路和相應的代碼: 1....