/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int Maxnumber(int* arr, int arrSize){
int i;
int max = arr[0];
int index = -1;
for(i = 0; i < arrSize; i++){
if(arr[i] >= max)
{
max = arr[i];
index = i;
}
}
return index;
}
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) {
if(numsSize == 0)
return NULL;
int maxIndex = Maxnumber(nums, numsSize);
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = nums[maxIndex];
node->left = constructMaximumBinaryTree(nums, maxIndex);
node->right = constructMaximumBinaryTree(nums + maxIndex + 1, numsSize - maxIndex - 1);
return node;
}
构造二叉树要用前序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2) {
if(!root1)
return root2;
if(!root2)
return root1;
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
如何处理空结点?
——返回另外一个树的子结点,不是子结点的值,因为两个树是一起操作做的。
递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* searchBST(struct TreeNode* root, int val) {
if(!root)
return NULL;
if(root->val == val){
return root;
}
if( val < root->val)
return searchBST(root->left, val);
else
return searchBST(root->right, val);
}
错误:
——没有想起二叉搜索树是已经排序了的
迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* searchBST(struct TreeNode* root, int val) {
while (root != NULL) {
if (root->val > val) root = root->left;
else if (root->val < val) root = root->right;
else return root;
}
return NULL;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int isBSTUtil(struct TreeNode* node, long long min, long long max)
{
if (node==NULL)
return 1;
if (node->val <= min || node->val >= max)
return 0;
return
isBSTUtil(node->left, min, node->val) && isBSTUtil(node->right, node->val, max);
}
bool isValidBST(struct TreeNode* root){
return isBSTUtil(root,LONG_MIN, LONG_MAX);
}
解题思路:比较时候不能只看当前子树是否满足搜查二叉树,因为逆这个子树满足了,不代表着正课二叉是满足搜查二叉树的。