Example 1:

Input: root = [4,2,7,1,3], val = 5 Output: [4,2,7,1,3,5]
package pep.Day70;
public class LeetCode_703_Insert_into_Binary_Search_Tree {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null)
return new TreeNode(val);
if (root.val < val)
root.right = insertIntoBST(root.right, val);
else
root.left = insertIntoBST(root.left, val);
return root;
}
}

No comments:
Post a Comment