思路:根据 “最大二叉树I”,可得,在数组中一定找到最大的那个节点为根节点,而根据题意,此时这个插入的节点一定在数组的末尾,所以我们只需在右子树上构造节点插入,当val的值大于此时节点的值时,把这个节点在新节点的左子树上就好
class Solution {
public:
TreeNode* insertIntoMaxTree(TreeNode* root, int val)
{
TreeNode*cur=root;
TreeNode*parent=nullptr;
while(cur)
{
if(cur->val<val)
{
if(!parent)//根节点
{
return new TreeNode(val,cur,nullptr);
}
TreeNode* node=new TreeNode(val,cur,nullptr);
parent->right=node;
return root;
}
else
{
parent=cur;
cur=cur->right;
}
}
parent->right=new TreeNode(val,nullptr,nullptr);
return root;
}
};