[99클럽 코테 스터디 13일차 TIL] 트리

sarah·2024년 8월 3일
0

programmers

목록 보기
13/21

문제

/**
 * 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;
 *     }
 * }
 */
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 searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) {
            return root;
        }
        

        if (val < root.val) {
            return searchBST(root.left, val);
        }
        
        
        return searchBST(root.right, val);
    }
}

해결방안

트리구조 이해 https://hoehen-flug.tistory.com/34

0개의 댓글