简体   繁体   English

二进制搜索树将节点乘以-1

[英]Binary Search Tree Multiply nodes by -1

Consider you have Binary Search Tree , in case multiply all nodes by -1 then can anybody please let me know if its still a Binary Search Tree ? 考虑到您有Binary Search Tree ,如果multiply all nodes by -1那么有人可以让我知道它是否仍然是Binary Search Tree吗?

Whether is it possible to write a function which converts it back to Binary Search Tree ? 是否可以编写将其转换回Binary Search Tree的函数?

In a binary search tree, all elements of a node's left subtree must be less than (or equal to, in some trees) the node and all elements of a node's right subtree must be greater than (or equal to, in some trees) the node. 在二叉搜索树中,节点的左子树的所有元素必须小于(或在某些树中),并且节点的右子树的所有元素必须大于(或在某些树中)节点。 If you multiply all the nodes by -1, you end up flipping this so that the left subtree of each node stores the greater values and the right subtree stores the lesser values. 如果将所有节点乘以-1,最终将其翻转,以使每个节点的左侧子树存储较大的值,而右侧子树存储较小的值。 To convert this back into a BST, you'd have to "flip" the BST by mirroring it. 要将其转换回BST,您必须通过镜像来“翻转” BST。 I'll leave the details of how to do that as an exercise; 在练习中,我将保留如何执行此操作的详细信息。 it's a classic CS problem with a beautiful recursive solution. 这是一个经典的CS问题,带有精美的递归解决方案。

Hope this helps! 希望这可以帮助!

Interesting problem. 有趣的问题。

In a Binary Search Tree , the structure of object graph indicates the sort ordering. Binary Search Tree ,对象图的结构指示排序顺序。

By multiplying all of the object by -1, it's now reverse sorted. 通过将所有对象乘以-1,现在将其反向排序。

EG: 例如:

3 4 8 9 12 

becomes

-3 -4 -8 -9 -12

So, how do you make this still maintain the Binary Search Tree property? 那么,如何使它仍然保持Binary Search Tree属性?

A binary tree would consist of two things: a graph of object nodes, and the knowledge on how to compare the objects. 一棵二叉树将由两件事组成:一个对象节点图,以及有关如何比较这些对象的知识。 The comparison function would look something like this: 比较功能如下所示:

 Compare(left, right) {
     return (left < right);
 }

If you perform a transformation on the values inside your binary tree, you can change its comparison function and then it will continue to behave as it should. 如果对二进制树中的值执行转换,则可以更改其比较函数,然后它将继续按应有的方式运行。

 myBinaryTree.comparisonFunction = function(left, right) { return (right < left) };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM