654. 最大二叉树
Posted zouma
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了654. 最大二叉树相关的知识,希望对你有一定的参考价值。
一、递归
TreeNode* recur(vector<int>& nums, int m, int n) int max = nums[m]; int mid = m; for (int i = m; i <= n; ++i) if (nums[i] > max) max = nums[i]; mid = i; TreeNode* root = new TreeNode(max); if(m<=mid-1) root->left = recur(nums, m, mid - 1); if(mid+1<=n) root->right = recur(nums, mid + 1, n); return root; TreeNode* constructMaximumBinaryTree(vector<int>& nums) int m = 0, n = nums.size() - 1; TreeNode* root = recur(nums, m, n); return root;
二、另一种递归思路,效率差
1 TreeNode* recur(TreeNode* root, int val) 2 3 TreeNode* node = new TreeNode(val); 4 if (!root) 5 return node; 6 else if (root->val < val) 7 8 node->left = root; 9 return node; 10 11 else 12 13 root->right = recur(root->right, val); 14 return root; 15 16 17 TreeNode* constructMaximumBinaryTree(vector<int>& nums) 18 if (nums.size() == 0) 19 return nullptr; 20 TreeNode* root = nullptr; 21 for (int i = 0; i < nums.size(); ++i) 22 23 root = recur(root, nums[i]); 24 25 return root; 26
三、单调栈,还没看懂
1 TreeNode* constructMaximumBinaryTree(vector<int>& nums) 2 int size = nums.size(); 3 if (size == 0) 4 return nullptr; 5 stack<TreeNode*> use; 6 TreeNode* root = new TreeNode(nums[0]); 7 TreeNode* last = root; 8 use.push(root); 9 for (int i = 1; i < size; ++i) 10 11 TreeNode* t = new TreeNode(nums[i]); 12 if (t->val > root->val) 13 root = t; 14 last = use.top(); 15 if (!use.empty()&&t->val > last->val) 16 17 use.pop(); 18 while (!use.empty() && t->val > use.top()->val) 19 20 last = use.top(); 21 use.pop(); 22 23 if (use.empty()) 24 25 t->left = last; 26 27 else 28 29 use.top()->right = t; 30 t->left = last; 31 32 33 else 34 35 use.top()->right = t; 36 37 use.push(t); 38 39 return root; 40
以上是关于654. 最大二叉树的主要内容,如果未能解决你的问题,请参考以下文章