Friday, April 29, 2022

Leet Code 701. Insert into a Binary Search Tree

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

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...