C 语言 层次遍历二叉树

已知二叉树如下图所示:

C 语言 层次遍历二叉树

反向水平顺序遍历

分别输出: 第三层: 4 , 5

第二层: 2, 3

第一层: 1

#include <stdio.h>
#include <stdlib.h>

struct node {
\tint data;
\tstruct node *left;
\tstruct node *right;
};
void printGivenLevel(struct node *root, int level);
int height(struct node *node);
struct node *newNode(int data);
void reverseLevelOrder(struct node *root)
{
\tint h = height(root);
\tint i;
\tfor (i = h; i >=1; i--) {
\t\tprintf("Level %d : {", i);
\t\tprintGivenLevel(root, i);
\t\tprintf("}\\n");
\t}
}
void printGivenLevel(struct node *root, int level)
{
\tif (root == NULL)
\t\treturn;
\tif (level == 1)
\t\tprintf("%d ", root->data);
\telse if (level > 1) {
\t\tprintGivenLevel(root->left, level-1);
\t\tprintGivenLevel(root->right, level-1);
\t}
}
int height(struct node *node)
{
\tif (node == NULL)
\t\treturn 0;
\telse {
\t\tint lheight = height(node->left);
\t\tint rheight = height(node->right);
\t\t
\t\tif (lheight > rheight) return (lheight + 1);
\t\telse return (rheight + 1);
\t}
}
struct node *newNode(int data)
{
\tstruct node *node = (struct node *)malloc(sizeof(struct node));
\tnode->data = data;
\tnode->left = node->right = NULL;
\treturn node;
}
int main(int argc, char *argv[]) {
\t
\tstruct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Level Order traversal of binary tree is \\n");
reverseLevelOrder(root);
\treturn 0;
}
/<stdlib.h>/<stdio.h>


分享到:


相關文章: