代码随想录算法训练营第十七天| 654.最大二叉树 617.合并二叉树 700.二叉搜索树中的搜索 98.验证二叉搜索树
654.最大二叉树
比较简单,直接上代码
1 TreeNode* constructMax_cursor(vector<int>& nums) 2 { 3 if (nums.size() == 0) return NULL; 4 //getMaxNum 5 int index = 0; 6 int max_ = INT_MIN; 7 for (int i = 0; i < nums.size(); i++) 8 { 9 if (max_ < nums[i]) 10 { 11 index = i; 12 max_ = nums[i]; 13 } 14 } 15 16 TreeNode* curNode = new TreeNode(max_); 17 18 //分割数组 19 vector<int> left = vector<int>(nums.begin(), nums.begin() + index); 20 21 vector<int> right = index + 1 != nums.size() ? 22 vector<int>(nums.begin() + index + 1, nums.end()) : vector<int>(nums.end(), nums.end()); 23 24 25 curNode->left = constructMax_cursor(left); 26 curNode->right = constructMax_cursor(right); 27 28 return curNode; 29 } 30 TreeNode* constructMaximumBinaryTree(vector<int>& nums) { 31 if (nums.size() == 0) return NULL; 32 33 return constructMax_cursor(nums); 34 }
617.合并二叉树
代码
1 TreeNode* mergeTrees_cur(TreeNode* root1, TreeNode* root2) 2 { 3 TreeNode* node = new TreeNode(); 4 if (!root1 && !root2) return NULL; 5 else if (root1 && root2) 6 { 7 node->val = root1->val + root2->val; 8 node->left = mergeTrees_cur(root1->left, root2->left); 9 node->right = mergeTrees_cur(root1->right, root2->right); 10 } 11 else if (root1 && !root2) 12 { 13 node->val = root1->val; 14 node->left = mergeTrees_cur(root1->left, NULL); 15 node->right = mergeTrees_cur(root1->right, NULL); 16 } 17 else if (!root1 && root2) 18 { 19 node->val = root2->val; 20 node->left = mergeTrees_cur(NULL, root2->left); 21 node->right = mergeTrees_cur(NULL, root2->right); 22 } 23 24 return node; 25 } 26 TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) 27 { 28 if (!root1 && !root2) return NULL; 29 return mergeTrees_cur(root1, root2); 30 }
700.二叉搜索树中的搜索
思路:
因为二叉搜索数是一个有序树,所以可以直接根据和根节点的大小,取匹配
代码:
1 TreeNode* searchBST(TreeNode* root, int val) { 2 TreeNode* result = NULL; 3 if (!root) return result; 4 5 while (root != NULL) 6 { 7 if (root->val == val) 8 { 9 return root; 10 } 11 else if (root->val > val) 12 { 13 root = root->left; 14 } 15 else 16 { 17 root = root->right; 18 } 19 } 20 return result; 21 }
98.验证二叉搜索树
中序遍历,保证从小到大
代码:
1 bool isValidBST(TreeNode* root) { 2 if (!root) return false; 3 vector<int> vals; 4 stack<TreeNode*> selected; 5 selected.push(root); 6 while (!selected.empty()) 7 { 8 auto cur_ = selected.top(); 9 if (cur_->left) 10 { 11 selected.push(cur_->left); 12 cur_->left = NULL; 13 } 14 else 15 { 16 if (vals.size()>0&&cur_->val <= vals.back()) 17 { 18 return false; 19 } 20 vals.push_back(cur_->val); 21 selected.pop(); 22 if (cur_->right) selected.push(cur_->right); 23 } 24 } 25 26 return true; 27 }