1. 程式人生 > 實用技巧 >構建表示式樹-(棧樹、中序遍歷)

構建表示式樹-(棧樹、中序遍歷)

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