Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
trees with reverse polish notation
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//Rextester.Program.Main is the entry point for your code. Don't change it. //Microsoft (R) Visual C# Compiler version 2.9.0.63208 (958f2354) using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { class Node { public int id;public int data = 0; public Node a = null,b = null; public Node(int ID){id = ID;} public Node(int ID, int Data){id = ID; data = Data;} public int sum() { if (a == null || b == null || id == 0) {return data;} switch(id) { case 1: return a.sum() + b.sum(); case 2: return a.sum() - b.sum(); case 3: return a.sum() * b.sum(); } return 0; } public override string ToString() => id == 0? data.ToString(): $"{(a.id != 0 ? "(":"")}{a.ToString()}{(a.id != 0 ? ")":"")} {(id == 1 ? "+":(id == 2 ? "-":"*"))} {(b.id != 0 ? "(":"")}{b.ToString()}{(b.id != 0 ? ")":"")}"; } public class Program { static Node NodeParse(string txt) { //nums and operator string nums = txt.Split('|')[0]; string operators = txt.Split('|')[1]; //parsing given values Stack<int> values = new Stack<int>(); foreach(string val in nums.Split(',')){values.Push(int.Parse(val));} //variables for parsing Stack<Node> temps = new Stack<Node>(); //parsing foreach(char oper in operators.ToCharArray()) { Node temp = new Node("+-*".IndexOf(oper)+1); switch (values.Count) { default: temp.a = new Node(0,values.Pop()); temp.b = new Node(0,values.Pop()); break; case 1: temp.a = new Node(0,values.Pop()); temp.b = temps.Pop(); break; case 0: temp.a = temps.Pop(); temp.b = temps.Pop(); break; } temps.Push(temp); } //returning return temps.Pop(); } public static void Main (string[] args) { /* Node root = new Node(1); root.a = new Node(0,2); root.b = new Node(3); root.b.a = new Node(0,3); root.b.b = new Node(0,2); */ string reversePolish = Console.ReadLine();// "2,3|-"; reversePolish = "10,3,4|*+"; //comment out this line for readline to work Node root = NodeParse(reversePolish); Console.WriteLine ($"{reversePolish} => {root.ToString()} = {root.sum()}"); } } }
4,3,5,12,-3|*+*-
Show compiler warnings
[
-
]
Show input
Compilation time: 0,22 sec, absolute running time: 0,11 sec, cpu time: 0,11 sec, average memory usage: 15 Mb, average nr of threads: 3, absolute service time: 0,34 sec
edit mode
|
history
|
discussion
10,3,4|*+ => 10 + (4 * 3) = 22