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

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. }







posted @ 2017-06-08 00:07  xiejunzhao  阅读(289)  评论(0编辑  收藏  举报