题解:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var flatten = function(root) {
if(!root) {
return;
}
flatten(root.left);
flatten(root.right);
let left = root.left;
let right = root.right;
root.left = null;
root.right = left;
let p = root;
while(p.right) {
p = p.right;
}
p.right = right;
};
题解:
/**
* 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) {
return build(nums, 0, nums.size() - 1);
}
TreeNode* build(const vector<int>& nums, int low, int high) {
if(low > high) {
return nullptr;
}
int index = low;
for(int i = low + 1; i <= high; i++) {
if(nums[i] > nums[index]) {
index = i;
}
}
TreeNode* root = new TreeNode(nums[index]);
root->left = build(nums, low, index - 1);
root->right = build(nums, index + 1, high);
return root;
}
};
题解

/**
* 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:
unordered_map<int, int> hash;
TreeNode* build(vector<int>& pre, int pleft, int pright,
vector<int>& ino, int ileft, int iright) {
if(pleft > pright) {
return nullptr;
}
TreeNode* root = new TreeNode(pre[pleft]);
int index;
for(int i = ileft; i <= iright; i++) {
if(ino[i] == pre[pleft]) {
index = i;
}
}
root->left = build(pre, pleft + 1, pleft + index - ileft,
ino, ileft, index - 1);
root->right = build(pre, pleft + index - ileft + 1, pright,
ino, index + 1, iright);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder, 0, preorder.size() - 1,
inorder, 0, inorder.size() - 1);
}
};