首页 > 代码库 > 572. 是否为另一棵二叉树的子树 Subtree of Another Tree
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();
}
}
null
572. 是否为另一棵二叉树的子树 Subtree of Another Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。