题解 | #二叉树遍历#

二叉树遍历

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

递归建树,子树为空返回NULL

#include <iostream>
using namespace std;
struct treeNode {
    char letter;
    treeNode* leftChild;
    treeNode* rightChild;
    treeNode(char c) {
        letter = c;
        leftChild = NULL;
        rightChild = NULL;
    }
};
treeNode* buildTree(string preOrderStr, string inOrderStr) {
    if (preOrderStr.size() == 0) {
        return NULL;
    }
    treeNode* newNode = new treeNode(preOrderStr[0]);

    int pos = inOrderStr.find(preOrderStr[0]);
    newNode->leftChild = buildTree(preOrderStr.substr(1, pos), inOrderStr.substr(0,
                                   pos));
    newNode->rightChild = buildTree(preOrderStr.substr(pos + 1),
                                    inOrderStr.substr(pos + 1));
    return newNode;
}
void postOrder(treeNode* root) {
    if (root == NULL) return;
    postOrder(root->leftChild);
    postOrder(root->rightChild);
    cout << root->letter;
}
int main() {
    string a, b;
    while (cin >> a >> b) { // 注意 while 处理多个 case
        treeNode* tree = buildTree(a, b);
        postOrder(tree);
        cout <<  endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

10-22 12:03
山东大学 Java
程序员小白条:26届一般都得有实习,项目可以随便写的,如果不是开源社区的项目,随便包装,技术栈也是一样,所以本质应该找学历厂,多投投央国企和银行,技术要求稍微低一点的,或者国企控股那种,纯互联网一般都得要干活
应届生简历当中,HR最关...
点赞 评论 收藏
分享
面了100年面试不知...:今年白菜这么多,冬天可以狂吃了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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