题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

难点在于递归建树

#include <ios>
#include <iostream>
using namespace std;
struct treeNode {
    char c;
    treeNode* leftChild;
    treeNode* rightChild;
    treeNode(char ch) {
        c = ch;
        leftChild=NULL;
        rightChild=NULL;
    }
};
string nodeStr;
int pos;
treeNode* buildTree() {
    char c=nodeStr[pos++];
    if (c == '#') {
        return NULL;
    }
    treeNode* newNode = new treeNode(c);
    newNode->leftChild = buildTree();
    newNode->rightChild = buildTree();
    
    return newNode;
}
void inOrder(treeNode* root) {
    if (root == NULL) return;
    inOrder(root->leftChild);
    cout << root->c << ' ';
    inOrder(root->rightChild);
}
int main() {

    while (cin >> nodeStr) { // 注意 while 处理多个 case
        pos=0;
        treeNode* root = buildTree();
        inOrder(root);
        cout  << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

投递长鑫存储等公司9个岗位
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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