572. Subtree of Another Tree 是否为另一棵二叉树的子树

本文介绍了一种通过先序遍历将二叉树转换为字符串的方法,以此来判断一棵二叉树是否为另一棵二叉树的子树。通过递归地遍历二叉树并使用特定符号表示节点是否存在,最终比较两个字符串来实现子树的判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4 
  / \
 1   2
Return  true , because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2
Return  false .

题意:判断一棵二叉树是否为另一 二叉树的子树
解法:先序遍历二叉树,并生成字符串(用#表示孩子节点是否为null的情况),判断字符串的包含关系


   
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public bool IsSubtree(TreeNode s, TreeNode t) {
  12. string s1 = Tree2String(s);
  13. string s2 = Tree2String(t);
  14. return s1.Contains(s2) || s2.Contains(s1);
  15. }
  16. static public string Tree2String(TreeNode root) {
  17. if (root == null) {
  18. return "";
  19. }
  20. StringBuilder sb = new StringBuilder();
  21. Stack<TreeNode> stack = new Stack<TreeNode>();
  22. TreeNode current = root;
  23. stack.Push(current);
  24. while (stack.Count != 0) {
  25. TreeNode popelem = stack.Pop();
  26. /**
  27. * 用#表示孩子节点是否为null的情况
  28. * 用","号分隔节点是防止"12##"和"2##"这种情况
  29. * ",12##",",2##"
  30. */
  31. if (popelem == null) {
  32. sb.Append("#");
  33. } else {
  34. sb.Append(popelem.val);
  35. }
  36. if (popelem != null) {
  37. stack.Push(popelem.right);
  38. stack.Push(popelem.left);
  39. }
  40. }
  41. return sb.ToString();
  42. }
  43. }







转载于:https://www.cnblogs.com/xiejunzhao/p/2877577c422f55b8b5227240bf375479.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值