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的情况),判断字符串的包含关系
/**
* 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();
}
}
时间: 2024-10-12 17:40:49