LeetCode 998: Maximum Binary Tree II Solution
Master LeetCode problem 998 (Maximum Binary Tree II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
998. Maximum Binary Tree II
Problem Explanation
Explanation
To solve this problem, we can perform a recursive approach. We need to handle three cases:
- If the root is null, we create a new node with the given value
valand return it. - If the given value
valis greater than the root's value, we create a new node with valueval, where the left child is the current root and the right child is null. - If the given value
valis less than the root's value, we recursively call the function on the right child of the current root until we find a suitable position to insert the new node.
The time complexity of this solution is O(n) in the worst case, where n is the number of nodes in the binary tree. The space complexity is also O(n) due to the recursive calls.
Solution Code
class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val > root.val) {
TreeNode newNode = new TreeNode(val);
newNode.left = root;
return newNode;
} else {
root.right = insertIntoMaxTree(root.right, val);
return root;
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 998 (Maximum Binary Tree II)?
This page provides optimized solutions for LeetCode problem 998 (Maximum Binary Tree II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 998 (Maximum Binary Tree II)?
The time complexity for LeetCode 998 (Maximum Binary Tree II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 998 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 998 in Java, C++, or Python.