LeetCode - Easy - 572. Subtree of Another Tree

布满荆棘的人生 2022-10-15 00:37 109阅读 0赞

Topic

  • Tree

Description

https://leetcode.com/problems/subtree-of-another-tree/

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.

Example 1:

1e5f9bb5fade74e48cd8a6299a897fbc.png

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

Example 2:

e17842c72af0219ea0936205429eacde.png

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

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].
  • − 1 0 4 < = r o o t . v a l < = 1 0 4 -10^4 <= root.val <= 10^4 −104<=root.val<=104
  • − 1 0 4 < = s u b R o o t . v a l < = 1 0 4 -10^4 <= subRoot.val <= 10^4 −104<=subRoot.val<=104

Analysis

考查前序遍历。

Submission

  1. import com.lun.util.BinaryTree.TreeNode;
  2. public class SubtreeOfAnotherTree {
  3. public boolean isSubtree(TreeNode root, TreeNode subRoot) {
  4. if(root == null ^ subRoot == null)
  5. return false;
  6. if(equals(root, subRoot))
  7. return true;
  8. return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
  9. }
  10. public boolean equals(TreeNode node1, TreeNode node2) {
  11. if(node1 == null ^ node2 == null)
  12. return false;
  13. if(node1 != null && node2 != null) {
  14. if(node1.val != node2.val)
  15. return false;
  16. return equals(node1.left, node2.left) && //
  17. equals(node1.right, node2.right);
  18. }
  19. return true;
  20. }
  21. }

Test

  1. import static org.junit.Assert.*;
  2. import static com.lun.util.BinaryTree.*;
  3. import org.junit.Test;
  4. public class SubtreeOfAnotherTreeTest {
  5. @Test
  6. public void test() {
  7. SubtreeOfAnotherTree obj = new SubtreeOfAnotherTree();
  8. assertTrue(obj.isSubtree(integers2BinaryTree(3, 4, 5, 1, 2), //
  9. integers2BinaryTree(4, 1, 2)));
  10. assertFalse(obj.isSubtree(integers2BinaryTree(3, 4, 5, 1, 2, null, null, null, null, 0),//
  11. integers2BinaryTree(4, 1, 2)));
  12. }
  13. }

发表评论

表情:
评论列表 (有 0 条评论,109人围观)

还没有评论,来说两句吧...

相关阅读