【例题1】938. 二叉搜索树的范围和 - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int rangeSumBST(struct TreeNode* root, int low, int high){
if(!root) return 0;
if(root->val >= low && root->val <= high)
return rangeSumBST(root->left,low,high) + rangeSumBST(root->right,low,high) + root->val;
else
return rangeSumBST(root->left,low,high) + rangeSumBST(root->right,low,high);
}
【例题2】LCR 175. 计算二叉树的深度 - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int calculateDepth(struct TreeNode* root) {
if(!root) return 0;
int count1 = calculateDepth(root->left);
int count2 = calculateDepth(root->right);
return 1+ (count1 > count2?count1:count2);
}
【例题3】104. 二叉树的最大深度 - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root){
if(!root) return 0;
int count1 = maxDepth(root->left);
int count2 = maxDepth(root->right);
return 1+ (count1 > count2?count1:count2);
}
【例题4】226. 翻转二叉树 - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root){
if(!root) return root;
struct TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
【例题5】797. 所有可能的路径 - 力扣(LeetCode)
int** p;
int temp[16];
int len;
//深度优先搜索
void dfs(int cur ,int dest,int** graph, int* graphColSize, int* returnSize, int** returnColumnSizes){
if(cur == dest){
int* change = (int*)malloc(sizeof(int)*len);
memcpy(change,temp,sizeof(int)*len);
p[*returnSize] = change;
(*returnColumnSizes)[(*returnSize)++] = len;
return;
}
for(int i=0;i<graphColSize[cur];i++){
int xx = graph[cur][i];
temp[len++] = xx;
dfs(xx,dest,graph,graphColSize,returnSize,returnColumnSizes);
len--;
}
}
int** allPathsSourceTarget(int** graph, int graphSize, int* graphColSize, int* returnSize, int** returnColumnSizes){
//规定初始状态
len = 0;
temp[len++] = 0;
p = (int**)malloc(sizeof(int*)*7000);
*returnSize = 0;
*returnColumnSizes = (int*)malloc(sizeof(int)*7000);
//实现函数 - 深度优先搜索
dfs(0, graphSize-1,graph,graphColSize,returnSize,returnColumnSizes);
return p;
}
标签:right,TreeNode,struct,int,第十五天,C语言,left,root,入门
From: https://blog.51cto.com/u_16188762/7870262