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;
}

相关文章:

  • 2021-10-28
  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2021-09-16
  • 2021-07-22
  • 2021-12-19
猜你喜欢
  • 2022-12-23
  • 2021-06-26
  • 2021-06-12
  • 2021-06-05
  • 2021-11-04
  • 2022-03-02
相关资源
相似解决方案