so i want to scan a string of an expression (ex: "1+2*3"), then put each of the element into a binary tree. So the operator will be the node, and the numbers will be the leaf. And below is my code:
At the end, i had no idea how to reverse and attach everything back to the 'treeRoot'. Can someone help me? Thank you very muchCode:double GrowTree(const string& expression) { char number[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; char operation[] = {'+', '-', '*', '/'}; string tempEx = expression; TreeNode<char>* treeRoot = new TreeNode<char>; TreeNode<char>* treeCurrent = new TreeNode<char>; treeRoot = NULL; treeCurrent = treeRoot; while(!tempEx.empty()) { for(int i=0; i<sizeof(number)/sizeof(char); i++) { if(tempEx[0] == number[i]) { TreeNode<char>* newLeaf = new TreeNode<char>; newLeaf->Value = tempEx[0]; if ( treeCurrent == NULL ) { treeRoot = treeCurrent = newLeaf; }else { treeCurrent->Right = newLeaf; } } } //if find any operator sign if( (tempEx[0] == '+' || tempEx[0]=='-')) { if(treeCurrent->Right == NULL) { TreeNode<char>* newRoot = new TreeNode<char>; newRoot->Value = tempEx[0]; //the operator will become the root newRoot->Left = treeRoot; treeCurrent = newRoot; //treeRoot->Right = treeCurrent; }else { TreeNode<char>* newRoot = new TreeNode<char>; newRoot->Value = tempEx[0]; newRoot->Left = treeCurrent->Right; treeCurrent->Right = newRoot; treeCurrent = newRoot; //treeRoot->Right = treeCurrent; } }else { if ( (tempEx[0] == '*' || tempEx[0] == '/' )) { if(treeCurrent->Right == NULL) { TreeNode<char>* newChild = new TreeNode<char>; newChild->Value = tempEx[0]; //the operator will become the root newChild->Left = treeRoot; treeCurrent = newChild; //treeRoot->Right = treeCurrent; }else { TreeNode<char>* newChild = new TreeNode<char>; newChild->Value = tempEx[0]; newChild->Left = treeCurrent->Right; treeCurrent->Right = newChild; treeCurrent = newChild; //treeRoot->Right = treeCurrent; } } } tempEx.erase(tempEx.begin()); } return ValueOf(treeRoot); //This is where the function calculate the expression, which is another function }
I could have reduce the code a little bit at checking the operators, but you know. I'll reduce it later when i the whole thing works



LinkBack URL
About LinkBacks
. I'll reduce it later when i the whole thing works 


