Max Tree
Given an integer array with no duplicates. A max tree building on this array is defined as follow:
- The root is the maximum number in the array
- The left subtree and right subtree are the max trees of the subarray divided by the root number.
Construct the max tree by the given array.
Example
Given [2, 5, 6, 0, 3, 1]
, the max tree constructed by this array is:
6
/
5 3
/ /
2 0 1
Challenge
O(n) time and memory.
单调栈,每遍历到一个元素,将栈中小于该元素的结点合并,将合并后新的结点挂在当前结点的左侧。合并的时候,因为栈中的结点的值是递减的,所以直接将第二个结点挂下第一个结点的右侧。另外,这种树有个学名叫做笛卡树(Cartesian tree)。
1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 class Solution { 14 public: 15 /** 16 * @param A: Given an integer array with no duplicates. 17 * @return: The root of max tree. 18 */ 19 TreeNode* maxTree(vector<int> A) { 20 // write your code here 21 TreeNode *a, *b, *tmp; 22 stack<TreeNode*> stk; 23 int cur_max = INT_MIN; 24 for (int i = 0; i <= A.size(); ++i) { 25 if (i < A.size() && A[i] < cur_max) { 26 tmp = new TreeNode(A[i]); 27 stk.push(tmp); 28 } else { 29 b = NULL; 30 while (!stk.empty() && (i == A.size() || stk.top()->val < A[i])) { 31 b = stk.top(); stk.pop(); 32 if (!stk.empty()) a = stk.top()->right = b; 33 } 34 if (i < A.size()) { 35 tmp = new TreeNode(A[i]); 36 tmp->left = b; 37 stk.push(tmp); 38 } else { 39 stk.push(b); 40 } 41 } 42 } 43 return stk.top(); 44 } 45 };