主题:怎么简单地把算术式子"3*(7+1)/4+(17-5)填到二叉树中?
我不知道怎么简单地建一个二叉树,
结构图片
struct TreeNode {
string item;
TreeNode * left;
TreeNode * right;
TreeNode(string str){
item = str;
left = NULL;
right = NULL;
}
};
bool treeContains(TreeNode * root , string item)
{
if ( root = NULL )
{
return false;
}
else if ( item == root->item )
{
return true;
}
else if ( item < root->item )
{
return treeContains(root->left, item);
}
else
{
return treeContains(root->right,item);
}
}
void treeInsert(TreeNode * root, string newItem)
{
if ( root == NULL )
{
root = new TreeNode( newItem );
return;
}
else if ( newItem < root->item )
{
treeInsert( root->left, newItem );
}
else {
treeInsert( root->right, newItem );
}
}
#include "stdafx.h"
#include "binaryTree.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode * root = new TreeNode("+");
treeInsert(root->right,"-");
treeInsert(root->right->left,"17");
treeInsert(root->right->right,"5"); //这样做,太傻.
treeInsert(root->left,"*");
treeInsert(root->left->left,"3");
treeInsert(root->left->right,"/"); treeInsert(root->left->right->right,"4");
treeInsert(root->left->right->left,"+");
treeInsert(root->left->right->left->left,"7");
treeInsert(root->left->right->left->right,"1");
return 0;
}
[img]http://www.yanglihao.com/filesUploaded/QQ截图未命名.jpg[/img]
结构图片
struct TreeNode {
string item;
TreeNode * left;
TreeNode * right;
TreeNode(string str){
item = str;
left = NULL;
right = NULL;
}
};
bool treeContains(TreeNode * root , string item)
{
if ( root = NULL )
{
return false;
}
else if ( item == root->item )
{
return true;
}
else if ( item < root->item )
{
return treeContains(root->left, item);
}
else
{
return treeContains(root->right,item);
}
}
void treeInsert(TreeNode * root, string newItem)
{
if ( root == NULL )
{
root = new TreeNode( newItem );
return;
}
else if ( newItem < root->item )
{
treeInsert( root->left, newItem );
}
else {
treeInsert( root->right, newItem );
}
}
#include "stdafx.h"
#include "binaryTree.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode * root = new TreeNode("+");
treeInsert(root->right,"-");
treeInsert(root->right->left,"17");
treeInsert(root->right->right,"5"); //这样做,太傻.
treeInsert(root->left,"*");
treeInsert(root->left->left,"3");
treeInsert(root->left->right,"/"); treeInsert(root->left->right->right,"4");
treeInsert(root->left->right->left,"+");
treeInsert(root->left->right->left->left,"7");
treeInsert(root->left->right->left->right,"1");
return 0;
}
[img]http://www.yanglihao.com/filesUploaded/QQ截图未命名.jpg[/img]