二叉树的前序遍历
力扣原题链接:https://leetcode.cn/problems/binary-tree-preorder-traversal/
int TreeSize(struct TreeNode* root)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
void _preorder(struct TreeNode* root, int* a, int* pi)
{
if(root == NULL)
return;
a[(*pi)++] = root->val;
//++(*pi);
_preorder(root->left, a, pi);
_preorder(root->right, a, pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int size = TreeSize(root);//节点个数
int* a = (int*)malloc(sizeof(int) * size);//动态开辟数组
int i = 0;
_preorder(root, a, &i);//记得传过去的是i的地址
*returnSize = size;
return a;//要求的是我们传去一个数组
}
其实,我们在使用C语言的时候,就发现C语言的缺陷了,C语言没有自己的容器,不支持泛型编程。如果我们会C++的话,使用库里面的容器,大小不需要我们计算,他自己会算。
class Solution {
public:
void preorder(TreeNode* root, vector<int>& res)//引用
{
if(root == NULL)
return;
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
};
我们掌握了二叉树的前序遍历,中序和后序遍历只需要改一下根、左子树、右子树的访问次序就可以了。
二叉树的最大深度
原题链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/submissions/
我们采用分治的思想,如果根为0,就返回0,如果根不为0,我们就返回根的左子树的深度和根的右子树的深度较大的那一个,然后 + 1。
int maxDepth(struct TreeNode* root){
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
平衡二叉树
原题链接:https://leetcode.cn/problems/balanced-binary-tree/
int maxDepth(struct TreeNode* root){
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
bool isBalanced(struct TreeNode* root){
if(root == NULL)
return true;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return abs(leftDepth - rightDepth) < 2 //abs函数是取绝对值函数
&& isBalanced(root -> left)
&&isBalanced(root->right);
}
清华大学计算机历年考研复试上机题
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode
{
char val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
TreeNode* CreatTree(char* a, int* pi)
{
if (a[*pi] == '#');
{
++(*pi);
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
if (root == NULL)
{
printf("malloc fail\n");
exit(-1);
}
root->val = a[*pi];
++(*pi);
root->left = CreatTree(a, pi);
root->right = CreatTree(a, pi);
return root;
}
void InOrder(TreeNode* root)
{
if (root == NULL)
return;
InOrder(root->left);
printf("%c ", root->val);
InOrder(root->right);
}
int main()
{
char str[100];
scanf("%s", str);
int i = 0;
TreeNode* root = CreatTree(str, &i);
InOrder(root);
return 0;
}
总结:二叉树的很多问题可以采用递归的方式巧妙的解决