998. Maximum Binary Tree II(最大二叉树II)
题目描述
方法思路
Q1:Why to the right and not to the left?
Always go right since new element will be inserted at the end of the list.
Q2:why if(root.val<v){
TreeNode node = new TreeNode(v);
node.left=root;
return node;
},rather than if(root.val<v){
TreeNode node = new TreeNode(v);
node.right=root;
return node;
};
Is it just follow the example?
Approach1: iterative
Search on the right, find the node that cur.val > val > cur.right.val
Then create new node TreeNode(val),
put old cur.right as node.left,
put node as new cur.right.
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
TreeNode node = new TreeNode(val), cur = root;
if (root.val < val) {
node.left = root;
return node;
}
while (cur.right != null && cur.right.val > val) {
cur = cur.right;
}
node.left = cur.right;
cur.right = node;
return root;
}
Approach2:recursive
这道题目描述的不是很清楚感觉上。(tricky!)
The idea is to insert node to the right parent or right sub-tree of current node. Using recursion can achieve this:
If inserted value is greater than current node, the inserted goes to right parent
If inserted value is smaller than current node, we recursively re-cauculate right subtree
class Solution {
//Runtime: 2 ms, faster than 100.00%
//Memory Usage: 37 MB, less than 100.00%
public TreeNode insertIntoMaxTree(TreeNode root, int v) {
if(root==null)return new TreeNode(v);
if(root.val<v){
TreeNode node = new TreeNode(v);
node.left=root;
return node;
}
root.right=insertIntoMaxTree(root.right,v);
return root;
}
}