[LeetCode] Search in a Binary Search Tree (JS)

nRecode·2020년 9월 21일
0

Algorithm

목록 보기
13/48

문제

Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.

입출력 예

Example

Given the tree:
        4
       / \
      2   7
     / \
    1   3

And the value to search: 2

You should return this subtree:

      2     
     / \   
    1   3

접근

입력으로 들어는 val을 루트로 하는 하위트리를 return하는 문제이다. 현재 루트 노드의 값이 val과 같으면 return하고 같지 않으면 자식노드들을 탐색하게 하는데 left부터 조사하고 right를 조사하는 깊이우선 탐색을 사용해서 코드를 작성한다.

풀이

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} val
 * @return {TreeNode}
 */
var searchBST = function(root, val) {
    // val를 루트로 하는 하위트리를 return 
    // 현재 루트 노드의 값이 val과 같으면 return 
    // 같지 않으면 자식노드들을 탐색
    let binaryTree = null;
    let findTree = (curnode) =>{
        if(curnode === null){
            return ;
        }
        if(curnode.val === val){
            binaryTree = curnode;
            return ;
        }
        findTree(curnode.left);
        findTree(curnode.right);
        
    }
    
   findTree(root);
    return binaryTree;
    
};
profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN