码迷,mamicode.com
首页 > 其他好文 > 详细

由二叉树的中序遍历, 前序遍历, 构建二叉树

时间:2014-09-15 12:50:08      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:io   ar   for   sp   on   c   ad   new   ef   

struct TreeNode
{
  struct TreeNode* left;
  struct TreeNode* right;
  char elem;
};


TreeNode* BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
  if(length == 0)
  {
    return NULL;
  }
  TreeNode* node = new TreeNode;//Noice that [new] should be written out.
  node->elem = *preorder;
  int rootIndex = 0;
  for(;rootIndex < length; rootIndex++)//a variation of the loop
  {
    if(inorder[rootIndex] == *preorder)
    break;
  }
  node->left = BinaryTreeFromOrderings(inorder, preorder +1, rootIndex);
  node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
  std::cout<<node->elem<<std::endl;
  return node;
  }

  int main(int argc, char** argv){
  char* pr="GDAFEMHZ";
  char* in="ADEFGHMZ";

  BinaryTreeFromOrderings(in, pr, 8);

   printf("\n");

  return 0;

}

 

//或者直接输出后续遍历

struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
char elem;
};

void BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
if(length == 0)
{
//cout<<"invalid length";
return;
}
TreeNode* node = new TreeNode;//Noice that [new] should be written out.
node->elem = *preorder;
int rootIndex = 0;
for(;rootIndex < length; rootIndex++)
{
if(inorder[rootIndex] == *preorder)
break;
}
//Left
BinaryTreeFromOrderings(inorder, preorder +1, rootIndex);
//Right
BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
cout<<node->elem<<endl;
return;
}


int main(int argc, char* argv[])
{
printf("Hello World!\n");
char* pr="GDAFEMHZ";
char* in="ADEFGHMZ";

BinaryTreeFromOrderings(in, pr, 8);

printf("\n");
return 0;
}

 

由二叉树的中序遍历, 前序遍历, 构建二叉树

标签:io   ar   for   sp   on   c   ad   new   ef   

原文地址:http://www.cnblogs.com/barfoo/p/3972467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!