构建表达式树-(栈树、中序遍历)
import java.util.Stack; public class BinaryTreeExpression { public static void main(String[] args) { String[] str = {"a","b","+","c","d","e","+","*","*"}; Stack<binaryTree> stack = new Stack<>(); //栈树 binaryTree t1; binaryTree t2; binaryTree tree; treenode node = new treenode(); for (String s: str) { if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){ t1 = stack.pop(); t2 = stack.pop(); tree = new binaryTree(); node = new treenode(s); tree.setRoot(node); node.setLeft(t2.root); node.setRight(t1.root); stack.push(tree); }else { tree = new binaryTree(); tree.setRoot(new treenode(s)); stack.push(tree); } } tree = stack.peek(); //后缀表达式对应的表达式树 tree.infixOrder(); //将表达式树展开 } } //定义二叉树 class binaryTree { public treenode root; public void setRoot(treenode root) { this.root = root; } //定义树的三种遍历 public void preOrder() { if (this.root != null) { this.root.preOrder(); } else { System.out.println("当前二叉树为空,无法进行前序遍历"); } } public void infixOrder() { if (this.root != null) { this.root.infixOrder(); } else { System.out.println("当前二叉树为空,无法进行前序遍历"); } } public void postOrder() { if (this.root != null) { this.root.postOrder(); } else { System.out.println("当前二叉树为空,无法进行前序遍历"); } } } //构造节点 class treenode { private String str; private treenode left; private treenode right; public treenode(String str) { this.str = str; } public treenode() {} public void setLeft(treenode left) { this.left = left; } public void setStr(String str) { this.str = str; } public void setRight(treenode right) { this.right = right; } @Override public String toString() { return "treenode{" + "str='" + str + '\'' + '}'; } //定义前序遍历 public void preOrder() { System.out.println(this); if (this.left != null) { this.left.preOrder(); } if(this.right != null) { this.right.preOrder(); } } //定义中序遍历 public void infixOrder() { if (this.left != null) { this.left.infixOrder(); } System.out.println(this); if(this.right != null) { this.right.infixOrder(); } } //定义后序遍历 public void postOrder() { if (this.left != null) { this.left.postOrder(); } if(this.right != null) { this.right.postOrder(); } System.out.println(this); } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!