Skip to content

Commit 6d01869

Browse files
添加 0654.最大二叉树.md C语言版本
1 parent f3b1405 commit 6d01869

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

problems/0654.最大二叉树.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,35 @@ var constructMaximumBinaryTree = function (nums) {
356356
};
357357
```
358358

359+
## C
360+
```c
361+
struct TreeNode* traversal(int* nums, int left, int right) {
362+
//若左边界大于右边界,返回NULL
363+
if(left >= right)
364+
return NULL;
365+
366+
//找出数组中最大数坐标
367+
int maxIndex = left;
368+
int i;
369+
for(i = left + 1; i < right; i++) {
370+
if(nums[i] > nums[maxIndex])
371+
maxIndex = i;
372+
}
373+
374+
//开辟结点
375+
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
376+
//将结点的值设为最大数组数组元素
377+
node->val = nums[maxIndex];
378+
//递归定义左孩子结点和右孩子结点
379+
node->left = traversal(nums, left, maxIndex);
380+
node->right = traversal(nums, maxIndex + 1, right);
381+
return node;
382+
}
383+
384+
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize){
385+
return traversal(nums, 0, numsSize);
386+
}
387+
```
359388
360389
361390
-----------------------

0 commit comments

Comments
 (0)