/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { private string generatepreorderString(TreeNode s) { StringBuilder sb = new StringBuilder(); Stack<TreeNode> stacktree = new Stack<TreeNode>(); stacktree.Push(s); while (stacktree.Count > 0) { TreeNode popelem = stacktree.Pop(); if (popelem == null) { sb.Append(",#"); // Appending # inorder to handle same values but not subtree cases } else { sb.Append("," + popelem.val); } if (popelem != null) { stacktree.Push(popelem.right); stacktree.Push(popelem.left); } } return sb.ToString(); } public bool IsSubtree(TreeNode s, TreeNode t) { string spreorder = generatepreorderString(s); string tpreorder = generatepreorderString(t); return spreorder.Contains(tpreorder); } }
https://leetcode.com/problems/subtree-of-another-tree/#/description
补充一个使用python的实现,思路就是使用二叉树的先序遍历,将节点和空节点存储到字符串中,然后比较t是否是s的字串。
1 class Solution: 2 s_pre = "" 3 t_pre = "" 4 def preOrder(self,root): 5 if root!=None: 6 self.s_pre += '<'+ str(root.val) + '>' 7 self.preOrder(root.left) 8 self.preOrder(root.right) 9 else: 10 self.s_pre += '<x>' 11 12 def preOrder2(self,root): 13 if root!=None: 14 self.t_pre += '<' + str(root.val) + '>' 15 self.preOrder2(root.left) 16 self.preOrder2(root.right) 17 else: 18 self.t_pre += '<x>' 19 20 def isSubtree(self, s: 'TreeNode', t: 'TreeNode') -> 'bool': 21 self.preOrder(s) 22 self.preOrder2(t) 23 return self.t_pre in self.s_pre
执行效率还是比较高的。
再补充一个双层递归的实现,我是不喜欢这种方式的,而且执行效率也低。
1 class Solution: 2 def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: 3 if s == None: 4 return False 5 return self.isSubTreeWithRoot(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t) 6 7 def isSubTreeWithRoot(self,s,t): 8 if s == None and t == None: 9 return True 10 if s == None or t == None: 11 return False 12 if s.val != t.val: 13 return False 14 return self.isSubTreeWithRoot(s.left,t.left) and self.isSubTreeWithRoot(s.right,t.right)