题解 | #二叉树遍历#

二叉树遍历

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

#include<iostream>
#include<string>
using namespace std;
struct tree {
    char c;
    tree* lc;
    tree* rc;
    tree(char ch) {
        c = ch;
        lc = NULL;
        rc = NULL;
    }
};
string s;
int n, i;//n是s的长度,i是指向字符串的当前位置
tree* buildTree() {
    tree* root = new tree(s[i]); //类似于先序遍历,所以处理放在递归前
    if (i + 1 >= n)//可以理解成就是保护数组不越界 越界的肯定没东西啦
        return NULL;
    if (s[++i] != '#')
        root->lc = buildTree();//根左右 所以先递归左边
    if (i + 1 >= n)
        return NULL;
    if (s[++i] != '#')
        root->rc = buildTree();
    return root;
}
void inOrder(tree* t) {
    if (t == NULL)
        return;
    inOrder(t->lc);
    cout << t->c << ' ';
    inOrder(t->rc);
}
int main() {
    cin >> s;
    n = s.size();
    i = 0;
    tree* root = buildTree();
    inOrder(root);
}
// 64 位输出请用 printf("%lld")

全部评论
友友们没看懂的可以再问~考前攒人品惹
点赞 回复 分享
发布于 2024-03-28 00:10 广东

相关推荐

评论
点赞
收藏
分享

创作者周榜

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