打印二叉树的边界节点

#include "Tree.h"
using namespace std;
int getHeight(Node* head, int l)
{
    if(head == nullptr)
        return l;
    else
        return max(getHeight(head->left, l + 1), getHeight(head->right, l + 1));
}
void setEdgeMap(Node* head, int l, Node* edgeMap[][2])
{
    if(head == nullptr)
        return;
    edgeMap[l][0] = edgeMap[l][0] == nullptr ? head : edgeMap[l][0];
    edgeMap[l][1] = head;
    setEdgeMap(head->left, l + 1, edgeMap);
    setEdgeMap(head->right, l + 1, edgeMap);
}
void printLeaf(Node* head, int l, Node* m[][2])
{
    if(head == nullptr)
        return;
    if(head->left == nullptr && head->right == nullptr && head != m[l][0] && head != m[l][1])
        cout << head->value << endl;
    printLeaf(head->left, l + 1, m);
    printLeaf(head->right, l + 1, m);
}
void printEdge1(Node* head)
{
    if(head == nullptr)
        return;

    int height = getHeight(head, 0);
    Node* edgeMap[height][2];
    for(int i = 0; i < height; ++i)
    {
        edgeMap[i][0] = nullptr;
        edgeMap[i][1] = nullptr;
    }
    setEdgeMap(head, 0, edgeMap);
    for(int i = 0; i < height; ++i)
        cout << edgeMap[i][0]->value << endl;

    printLeaf(head, 0, edgeMap);

    for(int i = height - 1; i != 0; --i)
        cout << edgeMap[i][1]->value << endl;
}



void printfLeftEdge(Node* head, bool print)
{
    if(head == nullptr)
        return;
    if(print || (head->left == nullptr && head->right == nullptr))
        cout << head->value << endl;
    printfLeftEdge(head->left, print);
    printfLeftEdge(head->right, print && head->left == nullptr ? true : false);
}
void printfRightEdge(Node* head, bool print)
{
    if(head == nullptr)
        return;
    printfRightEdge(head->left, print && head->right == nullptr ? true : false);
    printfRightEdge(head->right, print);
    if(print || (head->left == nullptr && head->right == nullptr))
        cout << head->value << endl;
}
void printEdge2(Node* head)
{
    if(head == nullptr)
        return;
    cout << head->value << endl;
    if(head->left && head->right)
    {
        printfLeftEdge(head->left, true);
        printfRightEdge(head->right, true);
    }
    else
        printEdge2(head->left != nullptr ? head->left : head->right);
}
int main()
{
    Node* pNode0 = new Node(0);
    Node* pNode1 = new Node(1);
    Node* pNode2 = new Node(2);
    Node* pNode3 = new Node(3);
    Node* pNode4 = new Node(4);
    Node* pNode5 = new Node(5);
    Node* pNode6 = new Node(6);

    connectTree(pNode0, pNode1, pNode2);
    connectTree(pNode1, pNode3, pNode4);
    connectTree(pNode2, pNode5, pNode6);

    printEdge1(pNode0);
    cout << "==============" << endl;
    printEdge2(pNode0);
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80707396