创建树:

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