Print Edge Nodes (Boundary) of a Binary Tree
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.
Solution:
#include "stdafx.h"
#include <iostream>
using namespace std;
class Tree
{
public:
int val;
Tree* left;
Tree* right;
};
void buildTree(Tree*& tree, int n, int init)
{
if(n<0)
return;
else
{
if(!tree)
{
tree = new Tree();
tree->val = init;
}
tree->left = new Tree();
tree->left->val = 2 * tree->val;
tree->right = new Tree();
tree->right->val = 2 * tree->val +1;
buildTree(tree->left, n-1, tree->left->val);
buildTree(tree->right, n-1, tree->right->val);
}
}
void printLeftEdge(Tree* tree)
{
if(!tree)
return;
else
{
cout << tree->val << endl;
printLeftEdge(tree->left);
}
}
void printButtomEdge(Tree* tree)
{
if(!tree)
return;
else if(tree->left == NULL && tree->right == NULL)
{
cout << tree->val << endl;
}
else
{
printButtomEdge(tree->left);
printButtomEdge(tree->right);
}
}
void printRightEdge(Tree* tree)
{
if(!tree)
return;
else
{
printRightEdge(tree->right);
cout << tree->val << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Tree* tree = NULL;
int n = 4;
buildTree(tree,n,1);
printLeftEdge(tree);
printButtomEdge(tree);
printRightEdge(tree);
return 0;
}
浙公网安备 33010602011771号