/**
* 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 {
TreeNode parent = null;
int flag = -1;
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode result = insert(root, val);
return result;
}
private TreeNode insert(TreeNode root, int val) {
if(root == null) { // 최초에 빈 BST or 리프블록까지 온 경우
root = new TreeNode(val); // 신규 Node
if(flag == 0) parent.right = root; // 오른쪽에 insert
if(flag == 1) parent.left = root; // 왼쪽에 insert
return root;
}
if(root.val < val) { // 오른쪽
flag = 0;
parent = root;
insert(root.right, val);
}
else if (root.val > val) { // 왼쪽
flag = 1;
parent = root;
insert(root.left, val);
}
return root;
}
}
다시 푼거
/**
* 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) { // 빈 트리면 루트 노트로 삽입
return new TreeNode(val);
}
if(root.val < val) {
root.right = insertIntoBST(root.right, val);
}
if(root.val > val) {
root.left = insertIntoBST(root.left, val);
}
return root;
}
}
BST 삽입/삭제 참고 => https://youtu.be/xxADG17SveY
'JAVA > leetcode' 카테고리의 다른 글
[LeetCode] Binary Tree Preorder Traversal - Preorder/Inorder/Postorder (0) | 2021.08.11 |
---|---|
[LeetCode Medium] BST - Delete Node in a BST !! (0) | 2021.08.10 |
[LeetCoed] BST - Search in a Binary Search Tree (0) | 2021.08.10 |
[LeetCode Medium] BST - Binary Search Tree Iterator (0) | 2021.08.10 |
[LeetCode Medium] BST - Validate Binary Search Tree !! (0) | 2021.08.10 |