So I have just written a solution to binary tree insertion. It seems to be effecient but takes up so much space in comparison to others. I am wondering how I can get better at reducing space complexity in my solutions for DSA. Thanks!
Here is what I wrote:
/**
* 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) {
if(root == null) {
root = new TreeNode();
root.val = val;
return root;
}
if(val > root.val){
root.right = insertIntoBST(root.right, val);
}
else if (val < root.val){
root.left = insertIntoBST(root.left, val);
}
return root;
}
}