|
| 1 | +# Problem: https://leetcode.com/problems/subtree-of-another-tree/description/ |
| 2 | +=begin |
| 3 | +Given the roots of two binary trees root and subRoot, |
| 4 | +return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. |
| 5 | +A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. |
| 6 | +The tree tree could also be considered as a subtree of itself. |
| 7 | +=end |
| 8 | + |
| 9 | +# Definition for a binary tree node. |
| 10 | +# class TreeNode |
| 11 | +# attr_accessor :val, :left, :right |
| 12 | +# def initialize(val = 0, left = nil, right = nil) |
| 13 | +# @val = val |
| 14 | +# @left = left |
| 15 | +# @right = right |
| 16 | +# end |
| 17 | +# end |
| 18 | +# @param {TreeNode} root |
| 19 | +# @param {TreeNode} sub_root |
| 20 | +# @return {Boolean} |
| 21 | + |
| 22 | +# Solution 1 (Brute force recursive) |
| 23 | +def is_subtree(root, sub_root) |
| 24 | + return true if sub_root.nil? |
| 25 | + return false if root.nil? |
| 26 | + is_found = false |
| 27 | + if root.val == sub_root.val |
| 28 | + return true if is_same_tree(root, sub_root) |
| 29 | + end |
| 30 | + is_subtree(root.left, sub_root) || is_subtree(root.right, sub_root) |
| 31 | +end |
| 32 | + |
| 33 | +def is_same_tree(root1, root2) |
| 34 | + return true if root1.nil? and root2.nil? |
| 35 | + return false if root1.nil? or root2.nil? |
| 36 | + root1.val == root2.val and is_same_tree(root1.left, root2.left) and is_same_tree(root1.right, root2.right) |
| 37 | +end |
0 commit comments