求二叉树各节点的深度
给定一棵二叉树,想要知道每个结点的深度,其实就在二叉树建立的时候就可以完成啦。创建二叉树的过程是:首先创建根节点,然后递归创建其左右子节点。而左右子节点的深度是父节点深度+1。运用这个思想,我们在递归建立二叉树时就可以传递一个变量表示这个节点的深度就可以啦。代码如下:
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node
{
struct node *left,*right;
char val;
int deep;
}*tree;
tree create(int d)
{
tree root;
char a;
scanf("%c",&a);
//输入'.'表示是个空子树
if(a!='.')
{
root=(tree)malloc(sizeof(node));
root->val=a;
//传进来的变量就是该结点的深度
root->deep=d;
//左右子节点的深度加1
root->left=create(d+1);
root->right=create(d+1);
}
else
return NULL;
return root;
}
//先序遍历,输出每个结点的深度
void pre(tree root)
{
if(root)
{
printf("%c deep=%d\n",root->val,root->deep);
pre(root->left);
pre(root->right);
}
}
int main()
{
//树的根节点深度为1
tree t=create(1);
pre(t);
return 0;
}
例如这棵树:ABDF..GH..I..E..C..
先序遍历运行结果为: