|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * function TreeNode(val, left, right) { |
| 4 | + * this.val = (val===undefined ? 0 : val) |
| 5 | + * this.left = (left===undefined ? null : left) |
| 6 | + * this.right = (right===undefined ? null : right) |
| 7 | + * } |
| 8 | + */ |
| 9 | +/** |
| 10 | + * @param {TreeNode} root |
| 11 | + * @param {TreeNode} subRoot |
| 12 | + * @return {boolean} |
| 13 | + */ |
| 14 | +var isSubtree = function (root, subRoot) { |
| 15 | + // Make function to check two triangle is same or not |
| 16 | + const isSame = (root1, root2) => { |
| 17 | + // If both of root1 and root2 is null, return true |
| 18 | + if (!root1 && !root2) return true; |
| 19 | + // If one of root1 and root2 is null or root1.val is not equal to root2.val, return false |
| 20 | + if (!root1 || !root2 || root1.val !== root2.val) return false; |
| 21 | + // Compare each left and right value with recursive |
| 22 | + return isSame(root1.left, root2.left) && isSame(root1.right, root2.right); |
| 23 | + }; |
| 24 | + |
| 25 | + // Make dfs function to check nodes inside of root tree |
| 26 | + const dfs = (node) => { |
| 27 | + // if node is null, return false |
| 28 | + if (!node) return false; |
| 29 | + // Check triangle is equal to subRoot |
| 30 | + if (isSame(node, subRoot)) return true; |
| 31 | + // Check one of the left or right node is same with triangle |
| 32 | + return dfs(node.left) || dfs(node.right); |
| 33 | + }; |
| 34 | + // Execute dfs function |
| 35 | + return dfs(root); |
| 36 | +}; |
| 37 | + |
| 38 | +// TC: O(n*m) |
| 39 | +// SC: O(max(m,n)) |
0 commit comments