Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
trees with reverse polish notation
//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()}"); } } }
run
|
edit
|
history
|
help
2
Simple Selection Sort
Lambda Expression
Ccc
Fórum ➡ GroupJoin'ing Books and Orders ( with Zip'ped output ) ♦
HourCouter
Pet Name Generator
dsda
Selected Poetry of Rumi doy/poem#
23
іфи