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 2Given tree t:
4 / \ 1 2Return 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 / 0Given tree t:
4 / \ 1 2Return false.
解法:先序遍历二叉树,并生成字符串(用#表示孩子节点是否为null的情况),判断字符串的包含关系
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSubtree(TreeNode s, TreeNode t) {
string s1 = Tree2String(s);
string s2 = Tree2String(t);
return s1.Contains(s2) || s2.Contains(s1);
}
static public string Tree2String(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
stack.Push(current);
while (stack.Count != 0) {
TreeNode popelem = stack.Pop();
/**
* 用#表示孩子节点是否为null的情况
* 用","号分隔节点是防止"12##"和"2##"这种情况
* ",12##",",2##"
*/
if (popelem == null) {
sb.Append("#");
} else {
sb.Append(popelem.val);
}
if (popelem != null) {
stack.Push(popelem.right);
stack.Push(popelem.left);
}
}
return sb.ToString();
}
}