【问题标题】:Create a Binary Tree from postfix expression从后缀表达式创建二叉树
【发布时间】:2019-03-18 22:42:23
【问题描述】:

假设我有以下后缀表达式:5372-*-

我想根据这个表达式创建一棵二叉树。我的算法是:如果我的 char 是数字,如果它是运算符,则将其放入堆栈中,从堆栈中弹出两个元素并使它们成为运算符的子元素。然后将运算符压入堆栈。看起来它正在工作,但我无法连接我创建的小树。

我当前的代码是:

public void myInsert(char ch, Stack s) {
    if (Character.isDigit(ch)) // initial cond.
        s.push(ch);
    else {
        TreeNode tParent = new TreeNode(ch);
        TreeNode t = new TreeNode(s.pop());
        TreeNode t2 = new TreeNode(s.pop());
        tParent.right = t;
        tParent.left = t2;
        s.push(ch);
        System.out.println("par" + tParent.ch);
        System.out.println("cright" + tParent.right.ch);
        System.out.println("cleft" + tParent.left.ch);
    }
}

我的测试课:

Stack stree = new Stack();

    BST b = new BST();
    String str = "5-3*(7-2)";
    String postfix = b.convertToPosFix(str);
    System.out.println(postfix);

    for (char ch : postfix.toCharArray()) {
         b.myInsert(ch, stree);

    }

我的输出是:

par-
cright2
cleft7
par*
cright-
cleft3
par-
cright*
cleft5

【问题讨论】:

    标签: java tree binary-tree infix-notation


    【解决方案1】:

    使用StackTreeNodes,而不是Stack 的字符。毕竟你必须结合TreeNodes 而不是chars:

    public void myInsert(char ch, Stack<TreeNode> s) {
        if (Character.isDigit(ch)) {
            // leaf (literal)
            s.push(new TreeNode(ch));
        } else {
            // operator node
            TreeNode tParent = new TreeNode(ch);
    
            // add operands
            tParent.right = s.pop();
            tParent.left = s.pop();
    
            // push result to operand stack
            s.push(tParent);
        }
    }
    

    树节点

    public class TreeNode {
        public TreeNode right = null;
        public TreeNode left = null;
        public final char ch;
    
        TreeNode(char ch) {
            this.ch = ch;
        }
    
        @Override
        public String toString() {
            return (right == null && left == null) ? Character.toString(ch) : "(" + left.toString()+ ch + right.toString() + ")";
        }
    
    }
    

    主要

    public static TreeNode postfixToTree(String s) {
        Stack<TreeNode> stree = new Stack<>();
    
        BST b = new BST();
        for (char ch : s.toCharArray()) {
            b.myInsert(ch, stree);
        }
        return stree.pop();
    }
    
    public static void main(String[] args) {
        System.out.println(postfixToTree("5372-*-"));
        System.out.println(postfixToTree("512+4*+3−"));
        System.out.println(postfixToTree("51*24*+"));
    }
    

    这将打印出来

    (5-(3*(7-2)))
    ((5+((1+2)*4))−3)
    ((5*1)+(2*4))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      相关资源
      最近更新 更多