LeetCode 572. Subtree of Another Tree

原题链接在这里:https://leetcode.com/problems/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   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.

题解:

Traverse s 的每个节点,看把该节点当成root的subtree是否与t identical.

如果s 和 t本身都是null, 那么t也算s的subtree, 因为null 是本身null 的subtree.

Time Complexity: O(m*n). m是s的节点数. n是t的节点数. 对于s的每一个节点都做了一次以该节点为root的subtree 与 t的比较.

Space: O(logm). stack space, 一直找不到的时候会走到s的底部.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isSubtree(TreeNode s, TreeNode t) {
12         if(isSame(s, t)){
13             return true;
14         }
15         return s!=null && (isSubtree(s.left, t) || isSubtree(s.right,t ));
16     }
17     
18     private boolean isSame(TreeNode s, TreeNode t){
19         if(s == null && t == null){
20             return true;
21         }
22         
23         if(s == null || t == null){
24             return false;
25         }
26         
27         if(s.val != t.val){
28             return false;
29         }
30         
31         return isSame(s.left, t.left) && isSame(s.right, t.right);
32     }
33 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     bool isSubtree(TreeNode* root, TreeNode* subRoot) {
15         if(isSame(root, subRoot)){
16             return true;
17         }
18 
19         return root && (isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot));
20     }
21 
22     bool isSame(TreeNode* p, TreeNode* q){
23         if(!p && !q){
24             return true;
25         }
26 
27         if(!p || !q){
28             return false;
29         }
30 
31         return p->val == q->val && isSame(p->left, q->left) && isSame(p->right, q->right);
32     }
33 };

AC Python:

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, val=0, left=None, right=None):
 4 #         self.val = val
 5 #         self.left = left
 6 #         self.right = right
 7 class Solution:
 8     def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
 9         if self.isSame(root, subRoot):
10             return True
11         return root and (self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot))
12     def isSame(self, p, q):
13         if not p and not q:
14             return True
15         if not p or not q:
16             return False
17         if p.val != q.val:
18             return False
19         return self.isSame(p.left, q.left) and self.isSame(p.right, q.right)
20         

对s 和 t 分别做preorder traversal, 然后看t得到的string 是不是 s得到string的 substring.

遇到null TreeNode时要添加特别符号, 不然就不能区分 123, null, null 和 1, 2, 3. 也无法区分 1, null, 2 和 1, 2, null. 这两种情况.

Time Complexity: O(m+n). m是s的节点数. n是t的节点数.

Space: O(Math.max(m, n)). StringBuilder space.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public boolean isSubtree(TreeNode root, TreeNode subRoot) {
18         String sPreorder = preorderTraversal(root);
19         String tPreorder = preorderTraversal(subRoot);
20 
21         return sPreorder.contains(tPreorder);
22     }
23 
24     private String preorderTraversal(TreeNode root){
25         StringBuilder sb = new StringBuilder();
26         Stack<TreeNode> stk = new Stack<TreeNode>();
27         stk.push(root);
28         while(!stk.isEmpty()){
29             TreeNode tn = stk.pop();
30             if(tn == null){
31                 sb.append(",#");
32             }else{
33                 sb.append(","+tn.val);
34                 stk.push(tn.right);
35                 stk.push(tn.left);
36             }
37         }
38         return sb.toString();
39     }
40 }

AC Python:

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, val=0, left=None, right=None):
 4 #         self.val = val
 5 #         self.left = left
 6 #         self.right = right
 7 class Solution:
 8     def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
 9         rootPreorder = self.preorder(root)
10         subRootPreorder = self.preorder(subRoot)
11         return subRootPreorder in rootPreorder
12     def preorder(self, root):
13         res = []
14         self.dfs(root, res)
15         return "".join(res)
16     def dfs(self, root, res):
17         if not root:
18             res.append(",#")
19             return
20         res.append(f",{root.val}")
21         self.dfs(root.left, res)
22         self.dfs(root.right, res)

类似Same TreeBinary Tree Preorder Traversal.

posted @ 2017-06-21 15:56  Dylan_Java_NYC  阅读(503)  评论(0编辑  收藏  举报