您的位置:首页 > 其它

【LeetCode】Subtree of Another Tree 解题报告

2017-05-09 11:54 417 查看

【LeetCode】Subtree of Another Tree 解题报告

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/subtree-of-another-tree/#/description

题目描述:

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.


Ways

我的想法最初也是通过遍历的方法看两个树的遍历结果是否一致。那么我想只有通过前序遍历和中序遍历两个遍历才能确定结果,但是看了大神的想法之后发现自己想的太复杂,而且存在问题。

问题是可能存在不同的数字相同的遍历结果。

大神的方法是在当节点为空的时候给一个“#”表示,这样就能表示出不同的子树,因此只需要遍历一次就能得到结果。每次遍历到树的结尾的时候能够按照#区分,另外每个树的节点值之间用”,”分割。

在提交的时候又遇到一个问题,就是12和2的结果是一样的,那么我在每个遍历结果的开头位置再加上一个逗号就完美解决了。

另外注意,不要判断左右子树不为空再去遍历树,这样就不能添加上“#”了。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
StringBuilder spre = new StringBuilder();
StringBuilder tpre = new StringBuilder();
public boolean isSubtree(TreeNode s, TreeNode t) {
preOrder(s, spre.append(","));
preOrder(t, tpre.append(","));
System.out.println(spre.toString());
System.out.println(tpre.toString());
return spre.toString().contains(tpre.toString());
}
public void preOrder(TreeNode root, StringBuilder str){
if(root == null){
str.append("#,");
return;
}
str.append(root.val).append(",");
preOrder(root.left, str);
preOrder(root.right, str);
}
}


Date

2017 年 5 月 9 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: