c++ - 二叉树节点子节点的高效选择

标签 c++ binary-tree

我有以下代码:

        NodePtr bestChild = (diff < 0) ? node->child1 : node->child2;
        NodePtr otherChild = (diff < 0) ? node->child2 : node->child1;

有没有更有效的方法来设置 bestChild 和 otherChild 变量?

注意 difffloat 并且比较是相当长的操作。

我还尝试了以下解决方案:

        NodePtr bestChild = (diff < 0) ? node->child1 : node->child2;
        NodePtr otherChild = (bestChild == node->child2) ? node->child1 : node->child2;

在这种情况下我不做比较,但我不确定这是最好的方法。

最佳答案

或者:

NodePtr bestChild, otherChild;
if (diff < 0)
{
    bestChild = node->child1;
    otherChild = node->child2;
}
else
{
    bestChild = node->child2;
    otherChild = node->child1;
}

NodePtr children[2] = (diff < 0) ? {node->child1, node->child2} : {node->child2, node->child1};

或者保持原样,因为编译器可能会为您完成此操作。

关于c++ - 二叉树节点子节点的高效选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10187921/

相关文章:

android - Qt for Android - 未定义对 ANativeWindow_fromSurface 的引用

c++ - googletest测试框架c++:静态方法链接器错误

c++ - 将监视器方法作为线程参数传递 c++

c++ - 标准运算符的函数指针

algorithm - 给定一个 preOrder 和 inOrder 序列,可能有多少级阶 BST 序列?

c++ - 关于函数范围的基本 C++ 问题

c++ - 最小值不在二叉树中?

java - Java 在二叉树中插入元素

algorithm - 将一个 BST 转换为在结构上与其他最小插入次数相同的 BST

arrays - 如何计算具有一定高度的二叉搜索树的数组大小?