TC:
SC:
since the recursive method will be called
times
/**
* 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 insertIntoBST(TreeNode root, int val) {
return tree(root,val);
}
public TreeNode tree(TreeNode node, int val){
///base case
if(node ==null) return new TreeNode(val);
if(node.val > val){
node.left = tree(node.left,val);
}
else node.right = tree(node.right,val);
return node;
}
}
Top comments (0)