题解 | #二叉树遍历#

二叉树遍历

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

//二叉树的建立和二叉树的中序遍历
#include <iostream>
using namespace std;
struct TreeNode{
    char c;
    TreeNode* leftChild;
    TreeNode* rightChild;
};
TreeNode* Build(int& position, string str){
    char c=str[position++];
    if(c=='#') return NULL;
    TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
    root->c=c;
    root->leftChild=Build(position,str);
    root->rightChild=Build(position,str);
    return root;
}
void inOrder(TreeNode* root){
    if(root==NULL) return;
    inOrder(root->leftChild);
    printf("%c ",root->c);
    inOrder(root->rightChild);
}
int main(){
    string str;
    while(cin>>str){
        int position=0;
        TreeNode* root = Build(position,str);
        inOrder(root);
    }
    return 0;
}

全部评论

相关推荐

投递腾讯云智研发等公司6个岗位
点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务