给出TREE_INSERT过程的非递归版本(算法导论第三版12.3-1)
template<typename T>
void insert_recursive(BinaryTree<T>& tree,BinaryTreeNode<T>* root, BinaryTreeNode<T>* node)
{if(tree.root == nullptr){tree.root = node;return;}if(root == nullptr){root = tree.root;}if(node->key < root->key){if(root->left == nullptr){root->left = node;if(node!= nullptr)node->parent = root;}elseinsert_recursive(tree,root->left,node);}else{if(root->right == nullptr){root->right = node;if(node!= nullptr)node->parent = root;}elseinsert_recursive(tree,root->right,node);}
}
测试代码
void inorder_tree_walk(BinaryTreeNode<T> * node)
{if(node!= nullptr){inorder_tree_walk(node->left);std::cout<<node->key<<" ";inorder_tree_walk(node->right);}
}
BinaryTreeNode<int>* nodes[] = {new BinaryTreeNode<int>(15),new BinaryTreeNode<int>(6),new BinaryTreeNode<int>(18),new BinaryTreeNode<int>(3),new BinaryTreeNode<int>(7),new BinaryTreeNode<int>(17),new BinaryTreeNode<int>(20),new BinaryTreeNode<int>(2),new BinaryTreeNode<int>(4),new BinaryTreeNode<int>(13),new BinaryTreeNode<int>(9),};BinaryTree<int> binaryTree;for (auto i :nodes) {insert_recursive<int>(binaryTree, nullptr,i);}inorder_tree_walk(binaryTree.root);cout<<endl;
辅助类
BinaryTree
template<typename T>
class BinaryTree{
public:BinaryTreeNode<T>* root;BinaryTree(){root = nullptr;}
};
BinaryTreeNode链接地址