998. Maximum Binary Tree II
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
TreeNode node = root;
TreeNode parent = null;
while (node != null && val < node.val) {
parent = node;
node = node.right;
}
TreeNode newNode = new TreeNode(val);
newNode.left = node;
if (parent == null) {
root = newNode;
} else {
parent.right = newNode;
}
return root;
}
}
Last updated