Kodun işleyişi genel olarak şöyle: önce prefix ifadeden ağaç oluşturuyor sonra bu ağaçı Left-Right-Data(LRD) olarak okuyor.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//TR" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="tr"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Prefix to Postfix</title> </head> <body> <div id="result"></div> <script> // Verileri tutacağımız ağaç yaprak yapısı function Leaf(value,left,right) { this.value=value; this.left = left; this.right=right; } //Sonuç postFix'i atmak için boş değişken oluşturduk var postFix =""; //Operand ve Operator eklmeyi kontrol için oluşturduk var state = false; // Karakter operator mü diye kontrol ediyor var isOperator= function (value){ if(value=='+' || value=='-' || value=='*' || value=='/') return true; else return false; } // Operand'ı ağaç yapısına ekliyor var addOperand = function(operand,leaf){ if(isOperator(leaf.value)){ if( !state && leaf.left==null){ leaf.left = new Leaf(operand,null,null); state=true; } else if( !state && isOperator(leaf.left.value)) addOperand(operand,leaf.left); if( !state && leaf.right ==null){ leaf.right = new Leaf(operand,null,null); state=true; } else if( !state && isOperator(leaf.right.value)) addOperand(operand,leaf.right); } } // Operatörü ağaç yapısına ekliyor var addOperator = function(operator,leaf){ if(isOperator(leaf.value)){ if( !state && leaf.left==null){ leaf.left = new Leaf(operator,null,null); state=true; } else if( !state && isOperator(leaf.left.value)) addOperator(operator,leaf.left); if( !state && leaf.right ==null){ leaf.right = new Leaf(operator,null,null); state=true; } else if( !state && isOperator(leaf.right.value)) addOperator(operator,leaf.right); } } // Sol-Sağ-Veri akışına göre veriyi okuyup postFix'e atıyor var readLRD = function(tree){ if(tree.left!=null) readLRD(tree.left); if(tree.right!=null) readLRD(tree.right); postFix +=tree.value; } // prefix'ten postfix'e çevirme işlemi var prefixToPostfix = function(prefix){ if(prefix.length==1){ if(!isOperator(prefix)){ postFix=prefix; } else{ postFix="İlk değer operator olamaz"; } } else{ postFix =""; var leaf= new Leaf(prefix[0],null,null); for(i=1;i<=prefix.length;i++){ state=false; if(!isOperator(prefix[i])){ addOperand(prefix[i],leaf); } else if(isOperator(prefix[i])){ addOperator(prefix[i],leaf); } } } readLRD(leaf); //Sonuç var result = "Prefix :"+prefix +"<br> Postfix:"+postFix; // Sonucu sayfaya ekliyoruz document.getElementById("result").innerHTML=result; } // Çevirmek istediğimiz formülü buraya yazıyoruz prefixToPostfix("-*/+x23-y+3x5"); </script> </body> </html>