1.递归方式
int getLeave(TreeNode *p) {
if (p == NULL)
{
return 0;
}
if (p->leftChild == NULL && p->rightChild == NULL)
{
num++;
}
getLeave(p->leftChild);
getLeave(p->rightChild);
return num;
}
2.非递归方式(前序遍历时判断该节点是否为叶子节点)
int nonReGetLeaf() {
int count = 0;
Stack<TreeNode*> s;
TreeNode *currentNode = root;
int j = 0;
while (1) {
while (currentNode) {
if (currentNode->leftChildNULL && currentNode->rightChildNULL) {
count++;
}
else{}
s.Push(currentNode);
currentNode = currentNode->leftChild;
}
if (s.isEmpty()) { break; }
else {
currentNode = s.Top();
s.Pop();
currentNode = currentNode->rightChild;
}
}
return count;
}