cin/cout流完整解决二叉树问题!

这篇文档主要记录一下在“白板”的编程情况下,二叉树的结构体建立、一维数组赋值输入输出。
以二叉树的前序遍历为例: 因为C++ 有宏定义 #define NULL 0;
因此在赋值的时候 如果赋值为NULL(相当于0) 将其置为nullptr。
废话不多说 直接上代码一目了然:(非递归前序遍历):

#include <iostream>
using namespace std;
#include <string>
#include <stack>
struct TreeNode
{
    int val;
    TreeNode * left;
    TreeNode* right;
    TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
void pre_pring(TreeNode *root) {
    stack<TreeNode *> t;
    TreeNode *p = root;
    while (!t.empty()||p) {
        while (p != nullptr) {
            t.push(p);
            cout << t.top()->val << "-";
            p = p->left;
        }
        p = t.top();
        t.pop();
        p = p->right;
    }
}

void create_tree(TreeNode* &root, int a[], int len, int index)
{
    if (index >= len)
        return;
    root = new TreeNode(-1);
    root->val = a[index];
    if (root->val == 0) root = nullptr;
    else {
        root->left = nullptr;
        root->right = nullptr;
        create_tree(root->left, a, len, 2 * index + 1);
        create_tree(root->right, a, len, 2 * index + 2);
    }
}

int main() {
    int num[] = { 1,3,4,NULL,NULL ,5,6 };
    TreeNode *root = new TreeNode(-1);
    create_tree(root, num, 7, 0);
    pre_pring(root);
    system("pause");
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容