typedef struct TreeNode
{struct TreeNode *left;struct TreeNode *right;char val;
}TreeNode;typedef struct Result{TreeNode * root; //构建的树的根结点int used; //构建过程中用掉的val个数
} Result;
求二叉树中所有结点个数
void TreeSize(TreeNode *root, int *size){if (root == NULL){return;}(*size)++;TreeSize(root->left,size);TreeSize(root->right,size);}//递推的思想
int TreeSize2(TreeNode *root){if (root == NULL){return 0;}return 1 + TreeSize2(root->left) + TreeSize2(root->right);
}
求叶子结点个数
//求叶子结点个数
void LeafSize(TreeNode *root, int *leaf_size){if (root == NULL){return;}if (root->left == NULL && root->right == NULL){leaf_size++;}LeafSize(root->left, leaf_size);LeafSize(root->right, leaf_size);
}//递推_叶子结点
int LeafSize2(TreeNode *root){if (root == NULL){return 0;}if (root->left == NULL && root->right == NULL){return 1;}return LeafSize2(root->left) + LeafSize2(root->right);
}
求第k层结点个数
思路
- 左子树已知第K-1层结点个数left
- 右子树第K-1层结点个数 right
- 求第K层结点个数
left + right - 终止条件 :
空树 return 0
代码实现
int LevelK(TreeNode *root, int k)
{if (root == NULL){return 0;}//这里不是空树,层数只有1层if (k == 1){return 1;}//反回左边的层数+右边的层数,每回往下走,层数就要减一return LevelK(root->left, k - 1) + LevelK(root->right, k - 1);}
在二叉树中查找某一结点
思路
查找val = x的值
- 先看根的val
- 在根不是我们要找的情况下,去左子树继续查找
- 在左子树中也没有找到,继续去右子树中查找
- 空树 return NULL
代码实现
TreeNode *Find(TreeNode *root, char x){if (root == NULL){return NULL;}//根if (root->val == x){return root;}//左子树不为空就在左子树找TreeNode *result = Find(root->left, x);if (result != NULL){return result;}//左子树没找到//如果右子树没找到,那么整个树都找不到return Find(root->right, x);}
层序遍历
又称为广度优先遍历
思路
代码实现
//层序遍历
#include<queue>
void LevelorderTraversal(TreeNode *root)
{if (root == NULL){return;}std::queue<TreeNode *>qu;qu.push(root);while (!qu.empty()){TreeNode *front = qu.front();qu.pop();printf("%c", front->val);//如果有左孩子if (front->left != NULL){qu.push(front->left);}//如果有右孩子if (front->right != NULL){qu.push(front->right);}}
}
判断是否为完全二叉树
思路
代码实现
//判断二叉树是否为完全二叉树
#include<queue>
bool IsCompleteBinaryTree(TreeNode *root)
{if (root == NULL){return true;}std::queue<TreeNode *>qu;qu.push(root);while (1){TreeNode *front = qu.front();qu.pop();if (front == NULL){//遇到空结点了break;}qu.push(front->left);qu.push(front->right);}//检查队列中是否还有非空结点while(!qu.empty()){TreeNode *front = qu.front();qu.pop();if (front != NULL){return false;}}return true;}