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.
题意
判断一个树t是否与另一个树s的子树相同。
思路
- dfs处理。递归遍历s,对每个结点判断以该结点为根的子树是否与t相同。
- 官方解答中的另一种方法:对两树进行前序遍历,得到类似”#1lnullrnull”的字符串ss和tt,判断tt是否是ss的子串。
代码实现 - dfs
class Solution {public boolean isSubtree(TreeNode s, TreeNode t) {// t一定不为nullif (s == null) {return false;}return judge(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);}private boolean judge(TreeNode s, TreeNode t) {if (s == null && t == null) {return true;} else if (s == null || t == null || s.val != t.val) {return false;}return judge(s.left, t.left) && judge(s.right, t.right);}}
代码处理 - 前序遍历
class Solution {public boolean isSubtree(TreeNode s, TreeNode t) {String ss = preOrder(s, false);String tt = preOrder(t, false);return ss.indexOf(tt) != -1;}private String preOrder(TreeNode root, boolean isLeft) {if (root == null) {return isLeft ? "lnull" : "rnull";}return "#" + root.val + preOrder(root.left, true) + preOrder(root.right, false);}}
