写出TREE-PREDECESSOR的伪代码(算法导论第三版12.2-3)
TREE-PREDECESSOR(x)if x.left != NILreturn TREE-MAXIMUM(x.left)y = x.pwhile y != NIL and x == y.leftx = yy = y.preturn y
下面是c++代码
template<typename T>
BinaryTreeNode<T>* tree_predecessor(BinaryTreeNode<T>* node)
{if(node == nullptr) return node;if(node->left!= nullptr)return tree_maximum(node->left);BinaryTreeNode<T>* parent = node->parent;while (parent!= nullptr && node == parent->left){node = parent;parent = parent->parent;}return parent;
}
辅助类
BinaryTreeNode链接地址