/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { if(nums.size() == 0) return nullptr; int index = 0; for(int i = 1; i < nums.size(); i++){ if(nums[i] > nums[index]) index = i; } TreeNode* root = new TreeNode(nums[index]); if(nums.size() == 1) return root; vector<int> left(nums.begin(),nums.begin()+index); vector<int> right(nums.begin()+index+1,nums.end()); root->left = constructMaximumBinaryTree(left); root->right = constructMaximumBinaryTree(right); return root; } };
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { 15 if(root1 == nullptr) return root2; 16 if(root2 == nullptr) return root1; 17 root1->val += root2->val; 18 root1->left = mergeTrees(root1->left, root2->left); 19 root1->right = mergeTrees(root1->right, root2->right); 20 return root1; 21 } 22 };
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* searchBST(TreeNode* root, int val) { 15 if(root == nullptr) return nullptr; 16 if(root->val == val) return root; 17 if(root->val > val) return searchBST(root->left,val); 18 else return searchBST(root->right,val); 19 } 20 };
中序遍历,如果是严格递增则是二叉搜索树,否则不是
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 bool isValidBST(TreeNode* root) { 15 vector<int> vec; 16 ldr(root,vec); 17 for(int i = 1; i < vec.size(); i++){ 18 if(vec[i] <= vec[i-1]) return false; 19 } 20 return true; 21 } 22 private: 23 void ldr(TreeNode* root, vector<int>& vec){ 24 if(root == nullptr) return; 25 ldr(root->left,vec); 26 vec.push_back(root->val); 27 ldr(root->right,vec); 28 } 29 };
浙公网安备 33010602011771号