[JS] Subtree of Another Tree

2022. 8. 13. 13:07

🔒 문제 (LeetCode 572)

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

Constraints:

  • The number of nodes in the root tree is in the range [1, 2000].
  • The number of nodes in the subRoot tree is in the range [1, 1000].
  • -104 <= root.val <= 104
  • -104 <= subRoot.val <= 104

 

🌊 입출력

Example 1:

Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true

Example 2:

Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false

 


 

🔑 해결

🌌 알고리즘 - DFS

/**
 * 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 {TreeNode} subRoot
 * @return {boolean}
 */
var isSubtree = function(root, subRoot) {
    const areEqual = (node1, node2) => {
        if(!node1 || !node2) return !node1 && !node2;
        if(node1.val !== node2.val) return false;
        return areEqual(node1.left, node2.left) && areEqual(node1.right, node2.right);
    }
    
    const stack = [root];
    
    while(stack.length) {
        const node = stack.pop();
        if(!node) continue;
        if(areEqual(node, subRoot)) return true;
        stack.push(node.right, node.left);
    }
    
    return false;
};

'코딩테스트 (JS) > DFS | BFS' 카테고리의 다른 글

[JS] All Paths From Source to Target  (0) 2022.08.24
[JS] Shortest Path in Binary Matrix  (0) 2022.08.18
[JS] Number of Provinces  (0) 2022.08.12
[JS] Number of Islands  (0) 2022.08.12
[JS] Letter Case Permutation  (0) 2022.07.31

+ Recent posts