按從左到右順序加載二叉樹和打印二叉樹 (C++)

從配置數組中加載二叉樹,

例如:數組 [3, 9, 20, NULL, NULL, 15, 7],NULL代表節點不存在,按照這個假設,二叉樹的節點數據不能爲0.

此數組對應的二叉樹是

    3
   / \
  9  20
    /  \
   15   7

從上到下,左右到右打印改二叉樹,結果爲[3, 9, 20, 15, 7],程序如下:

#include<iostream>
#include <list>
#include <vector>
#include <queue>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

static void printChildren(list<TreeNode*> childList)
{
    for (auto child : childList)
    {
        cout << child->val;
    }
    
    list<TreeNode*> newChildList;
    for (auto child : childList)
    {
        if (child->left)
            newChildList.push_back(child->left);
        
        if (child->right)
            newChildList.push_back(child->right);
    }
    childList.clear();
    
    if (newChildList.size() > 0)
        printChildren(newChildList);
}

static void loadChildren(list<TreeNode*> &nodeList, int i, int array[], int len)
{
    list<TreeNode*> childList;
    for (auto iter = nodeList.begin(); iter != nodeList.end(); iter++)
    {
        if (i < len && array[i] != 0)
        {
            TreeNode* node = *iter;
            node->left = new TreeNode(array[i]);
            childList.push_back(node->left);
        }
        i++;

        if (i < len && array[i] != 0)
        {
            TreeNode* node = *iter;
            node->right = new TreeNode(array[i]);
            childList.push_back(node->right);
        }
        i++;
    }
    nodeList.clear();

    if (childList.size() > 0)
    {
        loadChildren(childList, i, array, len);
    }
}

void main()
{
    int array[] = {3, 9, 20, NULL, NULL, 15, 7};
    TreeNode* root = new TreeNode(array[0]);
    list<TreeNode*> nodeList;
    nodeList.push_back(root);
    loadChildren(nodeList, 1, array, sizeof(array) / sizeof(array[0]));
    
    list<TreeNode*> childList;
    childList.push_back(root);
    printChildren(childList);
    
    cout << endl;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章