创建树:

public void createBTree(String str) {
Stack<BTNode> st = new Stack<>();
BTNode p = null;
char ch;
boolean flag = true;//处理的是左子树
int n = str.length();
int i = 0;
while (i < n) {
ch = str.charAt(i);
if (ch == '(') {
st.push(p);
flag = true;
} else if (ch == ',') {
flag = false;
} else if (ch == ')') {
st.pop();
} else {//处理字符
p = new BTNode(ch);
if (root == null) {
root = p;
} else {
if (!st.empty()) {
if (flag) {
st.peek().lchild = p;
} else {
st.peek().rchild = p;
}
}
}
}
i++;
}
}
把构造出来的树,用括号表示

public String toString() {
this.changeToString(root);
return bstr;
}
private void changeToString(BTNode t) {
if (t != null) {
bstr += t.data;
if (t.lchild != null || t.rchild != null) {
//左子树和右子树
bstr += '(';
this.changeToString(t.lchild);
bstr += ',';
this.changeToString(t.rchild);
bstr += ')';
}
}
}
实例:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
String str = "A(B(D(F,),E),C(,G))";
BTree bt = new BTree();
bt.createBTree(str);
System.out.println("用括号表示法输出二叉树为:" + bt);
}
}
class BTree {
BTNode root;
String bstr = "";
public BTree() {
root = null;
}
public void createBTree(String str) {
Stack<BTNode> st = new Stack<>();
BTNode p = null;
char ch;
boolean flag = true;//处理的是左子树
int n = str.length();
int i = 0;
while (i < n) {
ch = str.charAt(i);
if (ch == '(') {
st.push(p);
flag = true;
} else if (ch == ',') {
flag = false;
} else if (ch == ')') {
st.pop();
} else {//处理字符
p = new BTNode(ch);
if (root == null) {
root = p;
} else {
if (!st.empty()) {
if (flag) {
st.peek().lchild = p;
} else {
st.peek().rchild = p;
}
}
}
}
i++;
}
}
public String toString() {
this.changeToString(root);
return bstr;
}
private void changeToString(BTNode t) {
if (t != null) {
bstr += t.data;
if (t.lchild != null || t.rchild != null) {
//左子树和右子树
bstr += '(';
this.changeToString(t.lchild);
bstr += ',';
this.changeToString(t.rchild);
bstr += ')';
}
}
}
}
class BTNode<E> {
E data;
BTNode lchild;
BTNode rchild;
public BTNode() {
}
public BTNode(E data) {
this.data = data;
}
}
版权声明:本文为weixin_51995229原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。