【树】572. 另一个树的子树

题目:

【树】572. 另一个树的子树

 

 

 

解法:

 

方法一:先序遍历

 1 class Solution {
 2     public boolean isSubtree(TreeNode s, TreeNode t) {
 3         String tree1 = preOrder(s, true);
 4         String tree2 = preOrder(t, true);
 5         return tree1.indexOf(tree2) >= 0;
 6     }
 7 
 8     private String preOrder(TreeNode node, boolean left) {
 9         if (node == null) {
10             if (left) return "lnull";
11             else return "rnull";
12         }
13 
14         return "#" + node.val + " " + preOrder(node.left, true) + " " + preOrder(node.right, false);
15     }
16 }

 

方法二:比较节点

 1 class Solution {
 2     public boolean isSubtree(TreeNode s, TreeNode t) {
 3         return traverse(s, t);
 4     }
 5 
 6     private boolean traverse(TreeNode s, TreeNode t) {
 7         return s != null && (equals(s, t) || traverse(s.left, t) || traverse(s.right, t));
 8     }
 9 
10     // 比较两棵树是否相等
11     private boolean equals(TreeNode t1, TreeNode t2) {
12         if (t1 == null && t2 == null) return true;
13         else if (t1 == null || t2 == null) return false;
14 
15         return t1.val == t2.val && equals(t1.left, t2.left) && equals(t1.right, t2.right);
16     }
17 }

 

上一篇:572.另一个树的子树


下一篇:p56 树t是否等于树s的子树 (leetcode 572)