二叉树的遍历互求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kl1411/article/details/79533010

已知前序、中序遍历,求后序遍历

#include <iostream>
#include <string>
using namespace std;
typedef struct node
{
       struct node* left;
       struct node* right;
       char val;
}TreeNode;
TreeNode *BinaryTreeFormorderings(string Preorder, string Inorder)
{
       int len = Preorder.size();
       if (len == 0)
              return NULL;
       TreeNode *node = new TreeNode;
       node->val = Preorder[0];  //node保存根节点
       int rootIndex = 0;
       while (rootIndex < len)  //找出中序遍历中根节点位置
       {
              if (Inorder[rootIndex] == Preorder[0])
                     break;
              ++rootIndex;
       }
       //左子树递归
       node->left = BinaryTreeFormorderings(Preorder.substr(1, rootIndex), Inorder.substr(0, rootIndex));
       //右子树递归
       node->right = BinaryTreeFormorderings(Preorder.substr(rootIndex + 1), Inorder.substr(rootIndex + 1));
       cout << node->val;  //输出后序遍历
       return node;
}
int main()
{
       string pr = "GDAFEMHZ";
       string in = "ADEFGHMZ";
       BinaryTreeFormorderings(pr, in);
       cout << endl;
       system("pause");
       return 0;
}

已知中序和后序遍历,求前序遍历

#include <iostream>
#include <string>
using namespace std;
typedef struct node
{
       struct node* left;
       struct node* right;
       char val;
}TreeNode;
TreeNode *BinaryTreePostorderings(string Postorder, string Inorder)
{
       int len = Postorder.size();
       if (len == 0)
              return NULL;
       TreeNode *node = new TreeNode;
       node->val = Postorder[len - 1];  //node保存根结点
       cout << node->val;  //输出前序遍历
       int rootIndex = 0;
       while (rootIndex < len)  //找出中序遍历中根结点的位置
       {
              if (Inorder[rootIndex] == Postorder[len - 1])
                     break;
              ++rootIndex;
       }
       //左子树递归
       node->left = BinaryTreePostorderings(Postorder.substr(0, rootIndex), Inorder.substr(0, rootIndex));
       //右子树递归
       node->right = BinaryTreePostorderings(Postorder.substr(rootIndex, len - (rootIndex + 1)), Inorder.substr(rootIndex + 1));
       return node;
}
int main()
{
       string pt = "AEFDHZMG";
       string in = "ADEFGHMZ";
       BinaryTreePostorderings(pt, in);
       cout << endl;
       system("pause");
       return 0;
}

已知前序和后序遍历,求中序遍历

结果不唯一,并不能完全确定一棵树。

猜你喜欢

转载自blog.csdn.net/kl1411/article/details/79533010