965. Univalued Binary Tree

题目来源:
 https://leetcode.com/problems/univalued-binary-tree/submissions/
自我感觉难度/真实难度:
 
题意:
 
分析:
 
自己的代码:
class Solution(object):
    def isUnivalTree(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.dsf(root.val,root)
    def dsf(self,val,roo):
        if not roo:return True
        if roo.val!=val:
            return False
        return self.dsf(val,roo.left) and self.dsf(val,roo.right)
代码效率/结果:

Runtime: 36 ms, faster than 52.18% of Python online submissions for Univalued Binary Tree.

 
优秀代码:
class Solution(object):
    def isUnivalTree(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        q=collections.deque()
        q.append(root)
        val=root.val
        while q:
            node=q.popleft()
            if not node: continue
            if val!=node.val:return False
            q.append(node.left)
            q.append(node.right)
        return True
代码效率/结果:

Runtime: 32 ms, faster than 97.16% of Python online submissions for Univalued Binary Tree.

 
自己优化后的代码:
 
反思改进策略:

1.对怎么使用迭代,还是不熟悉,只是会使用固定的模板

2.递归需要考虑的两个核心:递归结束的出口,哪个是递归变量

原文地址:https://www.cnblogs.com/captain-dl/p/10274473.html