We are given the root
node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.
Just as in the previous problem, the given tree was constructed from an list A
(root = Construct(A)
) recursively with the following Construct(A)
routine:
- If
A
is empty, returnnull
. - Otherwise, let
A[i]
be the largest element ofA
. Create aroot
node with valueA[i]
. - The left child of
root
will beConstruct([A[0], A[1], ..., A[i-1]])
- The right child of
root
will beConstruct([A[i+1], A[i+2], ..., A[A.length - 1]])
- Return
root
.
Note that we were not given A directly, only a root node root = Construct(A)
.
Suppose B
is a copy of A
with the value val
appended to it. It is guaranteed that B
has unique values.
Return Construct(B)
.
Example 1:
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]
Example 2:
Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]
Example 3:
Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]
题解:
在上一篇博客的基础上解的题
大概就是在给定的一颗二叉树上,额外附加一个值val,建立另一颗二叉树,这个二叉树的建立规则请查看上一篇博客。
思路:
(一)、初始化一个vector用来存放给定的二叉树中序遍历出来的数值,然后在vector尾端加上val。然后再开始建立一颗新的二叉树。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
if(!root)
return NULL;
vector<int>res;
Inorder(root,res);
res.push_back(val);
vector<TreeNode*>Root;
for(int i=0;i<res.size();i++)
{
TreeNode* add=new TreeNode(res[i]);
if(Root.empty())
Root.push_back(add);
else
{
while(!Root.empty()&&Root.back()->val<res[i])
{
add->left=Root.back();
Root.pop_back();
}
if(!Root.empty())
Root.back()->right=add;
Root.push_back(add);
}
}
return Root.front();
}
void Inorder(TreeNode* root,vector<int>& res)
{
if(!root)
return ;
Inorder(root->left,res);
res.push_back(root->val);
Inorder(root->right,res);
}
};
运行结果:
(二)、直接在原始的二叉树上寻找到val的插入点。
根据例子所示:附加值val是直接放在二叉树中序序列的最后的。所以:
假设:node代表当前节点,prev代表node的父节点
1.重复以下代码:
if(!node&&val<node->val) 继续,else 结束。
2.,则val应该是prev的右孩子,node应该是val的左孩子。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
TreeNode *node=root,*prev=NULL;
while(node&&val<node->val)
{
prev=node;
node=node->right;
}
auto n=new TreeNode(val);
if(prev)
prev->right=n;
else
root=n;
n->left=node;
return root;
}
};