二叉树遍历的简单应用
看看二叉树的所有叶节点并求树高
可以在前序遍历的基础上稍加判断就能求出叶节点
(即判断它有无左子树和右子树)
typedef struct TreeNode * BinTree;
typedef BinTree Position;
typedef int ElementType;
struct TreeNode{
ElementType d;
BinTree Left;
BinTree Right;
};
查看叶节点的代码
void ChildPrint(BinTree BT){
if(BT){
if(!BT->Left && !BT->Right){
printf("%d",BT->d);
}
ChildPrint(BT->Left);
ChildPrint(BT->Right);
}
}
求树高,我们可以由后序遍历改过来
我们可以用递归的思想,求出左右树高更大的+1即可
int Height(BinTree BT){
int h_l,h_r,H;
if(BT){
h_l = Height(BT->Left);
h_r = Height(BT->Right);
H = h_l > h_r ? h_l : h_r;
return(H + 1);
}
else return 0;
}