class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
TreeNode curr = root;
TreeNode parent = new TreeNode();
TreeNode dummy = parent;
parent.right = root;
while(parent != null){
if(curr == null || val >= curr.val){
TreeNode insertNode = new TreeNode(val);
insertNode.left = curr;
parent.right = insertNode;
return dummy.right;
}else{
parent = curr;
curr = curr.right;
}
}
return dummy.right;
}
}
class Solution {
int index = 0;
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
int [] map = new int[101];
mapToArray(root,map);
map[index] = val;
return buildTree(map,0,index);
}
public void mapToArray(TreeNode root, int [] map){
if(root == null){
return;
}
mapToArray(root.left,map);
map[index++] = root.val;
mapToArray(root.right,map);
}
public TreeNode buildTree(int [] map,int start,int end){
if(start > end){
return null;
}
int ans = start;
int max = map[start];
for(int i = start+1;i <= end;++i){
if(map[i] > max){
ans = i;
max = map[i];
}
}
TreeNode root = new TreeNode(map[ans]);
root.left = buildTree(map,start,ans-1);
root.right = buildTree(map,ans+1,end);
return root;
}
}
class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
if(root == null || val >= root.val){
TreeNode insertNode = new TreeNode(val);
insertNode.left = root;
return insertNode;
}else{
root.right = insertIntoMaxTree(root.right,val);
}
return root;
}
}
作者:Coder_Jenny
链接:https://leetcode.cn/problems/maximum-binary-tree-ii/solution/by-coder_jenny-g73d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。