代码改变世界

print a complete binary tree anti-clockwise

2010-10-01 20:46  wansishuang  阅读(299)  评论(0编辑  收藏  举报

Print all edge nodes of a complete binary tree anti-clockwise.
That is all the left most nodes starting at root, then the leaves left to right and finally all the rightmost nodes.
In other words, print the boundary of the tree.

Variant: Print the same for a tree that is not complete.

 

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

 

struct Node
{
    int val;
    Node * left;
    Node * right;
public:
    Node(int _val):val(_val), left(NULL), right(NULL){}
};

void print(Node * root, int l, int r)
{
    if(root->left == NULL)
    {
        cout<< root->val << endl;
        return;
    }
    if(root->right == NULL)
    {
        cout<< root->val << endl;
        return;
    }
    if(l == 1 && r == 1)
    {
         cout<< root->val << endl;
         print(root->left, 1, 0);
         print(root->right, 0, 1);
    }
    else if(l == 1)
    {
        cout<< root->val << endl;
        print(root->left, 1, 0);
        print(root->right, 0, 0);
    }
    else if(r == 1)
    {
        print(root->left, 0, 0);
        print(root->right, 0, 1);
        cout<< root->val << endl;
    }
    else
    {
        print(root->left, 0, 0);
        print(root->right, 0, 0);
    }
}
int main()
{
     Node * n1 = new Node(1);
    Node * n2 = new Node(2);
    Node * n3 = new Node(3);
    Node * n4 = new Node(4);
    Node * n5 = new Node(5);

    Node * n6 = new Node(6);
    Node * n7 = new Node(7);
    Node * n8 = new Node(8);
    Node * n9 = new Node(9);
    Node * n10 = new Node(10);

    Node * n11 = new Node(11);
    Node * n12 = new Node(12);
    Node * n13 = new Node(13);
    Node * n14 = new Node(14);
    Node * n15 = new Node(15);

    n1->left = n2;
    n1->right = n3;

    n2->left = n4;
    n2->right = n5;

    n3->left = n6;
    n3->right = n7;

    n4->left = n8;
    n4->right = n9;

    n5->left = n10;
    n5->right = n11;

    n6->left = n12;
    n6->right = n13;

    n7->left = n14;
    n7->right = n15;

    print(n1, 1, 1);

    return 0;
}