【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 日相关文章推荐
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree 解题报告
- LeetCode@Tree_572_Subtree_of_Another_Tree
- LeetCode 572 Subtree of Another Tree
- LeetCode - 572 - Subtree of Another Tree
- 【LeetCode】236.Lowest Common Ancestor of a Binary Tree(Medium)解题报告
- 【LeetCode】Lowest Common Ancestor of a Binary Search Tree 解题报告
- LeetCode 572: Subtree of Another Tree
- [Leetcode] 572. Subtree of Another Tree 解题报告
- 【Leetcode-easy-572】Subtree of Another Tree
- leetcode 572 Subtree of Another Tree
- 【LeetCode】Maximum Depth of Binary Tree 解题报告
- LeetCode-Lowest Common Ancestor of a Binary Search Tree-解题报告
- [Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree 解题报告
- leetcode 572 Subtree of Another Tree
- LeetCode(111) Minimum Depth of Binary Tree解题报告
- [LeetCode] Subtree of Another Tree 另一个树的子树
- LeetCode Subtree of Another Tree
- 【LeetCode】Diameter of Binary Tree 解题报告
- 【LeetCode】572.Subtree of Another Tree(Easy)解题报告
- LeetCode Subtree of Another Tree