100. Same Tree
题目来源:
自我感觉难度/真实难度:
题意:
分析:
自己的代码:
class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if self.PreOrder(p)==self.PreOrder(q): return True return False def PreOrder(self,cur): if not cur: return [] res=[] res.extend(self.PreOrder(cur.left)) res.append(cur.val) res.extend(self.PreOrder(cur.right)) return res
代码效率/结果:
有错,先序相同,树不一定同
优秀代码:
public boolean isSameTree2(TreeNode p, TreeNode q) { return (p != null && q != null && p.val == q.val && isSameTree2(p.left, q.left) && isSameTree2(p.right, q.right)) || (p == null && q == null); }
def isSameTree(self, p, q): if p and q: return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) return p is q
代码效率/结果:
p is q ,这里用了一些技巧,当p是None和q是None的时候,这个返回是True
当时其他情况,一个为空,一个不空,返回值是False
自己优化后的代码:
class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p is None and q is None: return True if p is None or q is None: return False return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
反思改进策略:
1.先要有正确的求解思路
2.递归是常用的套路