- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
= r; -6ren">
我有像这样的中缀表达式:
((source = id)AND (target= id) AND ( NOT( color != blue) OR ( age<= 23 )))
如何转换为如下 TreeMap 所示的二叉树。我刚开始用 javascript 编写代码,但不知道如何编写插入操作,尤其是像 NOT 这样的一元运算符。如何解决这个问题。
var Node = function(data,left,right){
this.data = data;
this.left = left;
this.right = right;
};
var BinaryTree = function(){
this.head = new Node(null,null,null);
};
BinaryTree.prototype.insert = function(data){
if(this.head.data == null){
this.head = new Node(data,null,null);
} else{
var current = this.head;
insert(current,data);
}
};
var insert = function(current,data){
// How to insert ?
};
最佳答案
正如昨晚所说,这里是我必须要说的重点:
图节点:
//abstract base-class
class GraphNode {
constructor(){
Object.defineProperty(this, "parent", {
writable: true,
//enumerable: false, //so it doesn't show up in JSON
value: null
})
}
compute(ctx){ throw new Error("not implemented") }
toString(){ throw new Error("not implemented") }
}
//leaf-nodes
class ValueNode extends GraphNode{
constructor(value){
super();
this.value = value;
}
compute(){ return this.value; }
toString(){ return JSON.stringify(this.value); }
}
class PropertyNode extends GraphNode{
constructor(property){
super();
this.property = property;
}
compute(ctx){ return ctx[this.property]; }
toString(){ return String(this.property); }
}
//tree-nodes
class UnaryNode extends GraphNode{
constructor(op, node){
if(!(node instanceof GraphNode)){
throw new Error("invalid node passed")
}
super();
this.op = op;
this.node = node;
node.parent = this;
}
compute(ctx){
var v = this.node.compute(ctx);
switch(this.op){
case "NOT": return !v;
}
throw new Error("operator not implemented '"+this.op+"'");
}
toString(){
return "( " + this.op + " " + this.node.toString() + " )";
}
}
UnaryNode.operators = ["NOT"];
class BinaryNode extends GraphNode{
constructor(op, l, r){
if(!(l instanceof GraphNode && r instanceof GraphNode)){
throw new Error("invalid node passed")
}
super();
this.op = op;
this.left = l;
this.right = r;
l.parent = this;
r.parent = this;
}
compute(ctx){
var l = this.left.compute(ctx);
var r = this.right.compute(ctx);
switch(this.op){
//logic operators
case "AND": return l && r;
case "OR": return l || r;
//comparison-operators
case "=": return l === r;
case "<=": return l <= r;
case ">=": return l >= r;
case "!=": return l != r;
case ">": return l > r;
case "<": return l < r;
//computational operators
case "+": return l + r;
case "-": return l - r;
case "*": return l * r;
case "/": return l / r;
}
throw new Error("operator not implemented '"+this.op+"'");
}
toString(){
return "( " + this.left.toString() + " " + this.op + " " + this.right.toString() + " )";
}
}
//also defines precendence
BinaryNode.operators = [
"*","/","+","-",
">","<","<=",">=","!=","=",
"AND","OR",
]
//dot is kind of special:
class DotNode extends BinaryNode{
constructor(l, r){
/*
if(!(l instanceof PropertyNode || l instanceof DotNode)){
throw new Error("invalid left node")
}
*/
if(!(r instanceof PropertyNode)){
throw new Error("invalid right node")
}
super(".", l, r);
}
compute(ctx){
//especially because of this composition:
//fetch the right property in the context of the left result
return this.right.compute( this.left.compute(ctx) );
}
toString(){
return this.left.toString() + "." + this.right.toString();
}
}
解析器:
function escapeForRegex(str){
return String(str).replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&');
}
//dynamically build my parsing regex:
var tokenParser = new RegExp([
//numbers
/\d+(?:\.\d*)?|\.\d+/.source,
//string-literal
// /["](?:\\[\s\S]|[^"])+["]|['](?:\\[\s\S]|[^'])+[']/.source,
//booleans
//"true|false",
//operators
[".", "(", ")"].concat(UnaryNode.operators, BinaryNode.operators)
.sort((a,b) => b.length-a.length) //so that ">=" is added before "=" and ">", for example
.map(escapeForRegex)
.join("|"),
//properties
//has to be after the operators
/[a-zA-Z$_][a-zA-Z0-9$_]*/.source,
//remaining (non-whitespace-)chars, just in case
//has to be at the end
/\S/.source
].map(s => "("+ s +")").join("|"), "g");
function parse(str){
var tokens = [];
//abusing str.replace() as a RegExp.forEach
str.replace(tokenParser, function(token, number, op, property){
if(number){
token = new ValueNode(+number);
//}else if(string){
// token = new ValueNode(JSON.parse(string));
//}else if(bool){
// token = new ValueNode(bool === "true");
}else if(property){
token = new PropertyNode(property);
}else if(!op){
throw new Error("unexpected token '"+token+"'");
}
tokens.push(token);
});
for(var i; (i=tokens.indexOf(".")) > -1; ){
tokens.splice(i-1, 3, new DotNode(tokens[i-1], tokens[i+1]))
}
for(var i,j; (i=tokens.lastIndexOf("(")) > -1 && (j=tokens.indexOf(")", i)) > -1;){
tokens.splice(i, j+1-i, process(tokens.slice(i+1, j)));
}
if(~tokens.indexOf("(") || ~tokens.indexOf(")")){
throw new Error("mismatching brackets");
}
return process(tokens);
}
function process(tokens){
UnaryNode.operators.forEach(token => {
for(var i=-i; (i=tokens.indexOf(token, i+1)) > -1;){
tokens.splice(i, 2, new UnaryNode(token, tokens[i+1]));
}
})
BinaryNode.operators.forEach(token => {
for(var i=1; (i=tokens.indexOf(token, i-1)) > -1;){
tokens.splice(i-1, 3, new BinaryNode(token, tokens[i-1], tokens[i+1]));
}
});
if(tokens.length !== 1){
console.log("error: ", tokens.slice());
throw new Error("something went wrong");
}
return tokens[0];
}
及其用法:
var tree = parse("((a.source = id)AND (target= id) AND ( NOT( color != blue) OR ( age<= 23 )))")
//var tree = parse("1=1=age+10>30"); //to test operator precedence
var data = {
id: 12345,
a: { source: 12345 },
target: 12345,
color: "#FF0",
blue: "#00F",
age: 20
}
console.log(tree.compute(data));
console.log(tree.toString());
console.log(JSON.stringify(tree, null, 2));
关于javascript - 二叉表达式树的中缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37469768/
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 Improve th
我在使用 fork 和 pipes 制作一个用于学习目的的简单程序时遇到了问题。我想要一个 child 向 parent 发送一些数据,然后这个( parent )再次将它发送给 child 。 结果
我正在制作一个需要同时做 3 件事的 python 脚本。什么是实现此目的的好方法,就像我听说的关于 GIL 的方法一样,我不再那么倾向于使用线程了。 脚本需要做的两件事将非常活跃,他们将有很多工作要
有没有办法运行sshd以便它可以(至少对于有限数量的登录)成功返回提示(可能是 busybox),即使 fork 不可用(例如,PID 不足)? 在我看来,这应该是可能的,例如,sshd 预 fork
我意识到 Bootstrap 将使用 v4 切换到 rem。但是,我使用的是当前版本 (v3),我想使用 rem。 原因?我希望网站上有可以为最终用户缩放字体大小的按钮。我相信最好的实现方式是使用 r
我试图在这个程序中将信息从子进程传递到父进程。这是到目前为止的代码,仍在清理它: #include #include #include #include main() { char *
我试图理解 fork 在 C 中是如何工作的,但我在某个地方误解了一些东西。 我去年遇到了一位教授给我的测试,但我无法回复它:我们有 3 个任务(进程或线程),伪代码如下: Th1 { display
我在使用 fork() 之类的东西时遇到了一些麻烦。 我正在开发一个 shell,用户可以在其中编写将像在普通普通 shell 中一样执行的命令。 我有一个像这样的主要功能: void Shell::
我有一个 Python 主进程,以及由主进程使用 os.fork() 创建的一组或多个 worker . 我需要将大型且相当复杂的数据结构从工作程序传递回主进程。您会为此推荐哪些现有库? 数据结构是列
我对这个 fork 语句很陌生,我不知道 C 程序上的 fork 方法。你能告诉我这段代码的三个可能的输出是什么吗? #include #include int main(void) {
for(i=0;i #include int main() { for(int i=0;i<2;i++) { if(fork()==0) { printf("Hi %d %d
背景 我正在用 C 语言编写一个共享库,与 LD_PRELOAD 动态链接,这意味着拦截和覆盖预加载它的应用程序的网络调用,例如 socket()、connect()、recv()、send()等 在
我是一名优秀的程序员,十分优秀!