题目:EPI
分别用递归和迭代两种方式完成。
递归版本较简单:
迭代版本:
shared_ptr<treenode> find_appear_first(const shared_ptr<treenode> &root, const int key)
{
shared_ptr<treenode> first = nullptr, cur = root;
while (cur)
{
if (cur->data > key)
cur = cur->left;
else if (cur->data < key)
cur = cur->right;
else
{
first = cur;
cur=cur->left;
}
}
return first;
}