赞
踩
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; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。