题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/6e732a9632bc4d12b442469aed7fe9ce

//递归的灵活运用
#include <iostream>
using namespace std;


struct TreeNode
{
    char data;
    TreeNode* leftchild;
    TreeNode* rightchild;
    TreeNode(char c): data(c),leftchild(NULL),rightchild(NULL){}
};

TreeNode* Build(string strq,string strz)
{
    if(strq.size()==0)return NULL;//该子树为空
    
    char c=strq[0];
    int position=strz.find(c);
    TreeNode* root=new TreeNode(c);
    root->leftchild=Build(strq.substr(1,position),strz.substr(0,position));
    root->rightchild=Build(strq.substr(position+1),strz.substr(position+1));

    return root;
}
void PostOrder(TreeNode* root)
{
    if(root==NULL)return;

    PostOrder(root->leftchild);
    PostOrder(root->rightchild);
    cout<<root->data;
}

int main() {
    string strq, strz;
    while (cin >> strq >> strz) {
        TreeNode* root=Build(strq,strz);
        PostOrder(root);
        cout<<endl;
    }
}

全部评论

相关推荐

本2硕9,秋招不想努力海投了
小何和:行情再不好也不可能拒绝你,不可能只要双9的
点赞 评论 收藏
分享
陈逸轩1205:才105 哥们在养生呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务