LeetCode94——Binary Tree Inorder Traversal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28306361/article/details/88525541

题目链接

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

代码

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if root == None:
            return []
        res = []
        nodes = []
        node = root
        while len(nodes) > 0 or node != None:
            while node != None:
                nodes.append(node)
                node = node.left
            node = nodes.pop()
            res.append(node.val)
            node = node.right
        return res

运行结果

Runtime: 52 ms, faster than 18.73% of Python3 online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.1 MB, less than 5.64% of Python3 online submissions for Binary Tree Inorder Traversal.

思考:

当初拿到这个题,我一看就想到了深搜,对嘛很简单,但是,实际上我第一次编译的代码没有通过,我尝试好久还是没有通过,于是我开始反思是哪里不对了,下面是原来写的代码

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if root == None:
            return []
        res = []
        nodes = [root]
        while len(nodes) > 0:
            temp_node = nodes.pop()
            if temp_node.left != None:
                nodes.append(temp_node)
                nodes.append(temp_node.left)
                continue
            if temp_node.left == None:
                res.append(temp_node.val)
                nodes.append(temp_node.right)
                continue
        return res

感觉是对的啊,先遍历左子树,当左子树为空的时候,输出根节点的值,然后遍历右子树,想了好久还是没想出来,报错。

Line 16: AttributeError: 'NoneType' object has no attribute 'left'

最后还是一步一步地调试,其实在上面的代码中,有两个问题!

扫描二维码关注公众号,回复: 5933393 查看本文章

1:上面直接把右节点append进去,没有考虑到当右节点是空的情况下,重新运行while循环部分,它是没有左节点的,因此产生了上面的错误,

2:在题目所给的示例中,当你遍历过3这个节点的时候,当重新处理2这个节点的时候,会再次进入到3这个节点,如此循环下去,程序无法停止!!!

对比一下两版代码,表面上看思路大致相同,但是实习运行过程中,对于细节的处理,第二版是非常不到位的,这也告诉了我两个道理

1:今后在编写之后,一定一定遇到问题不要急躁,既然已经报错,那么说明测试用例正好暴露了它的问题,只需要一步一步调试耐心解决就好

2:自己的写的代码一定自己照着逻辑走一遍,不要想当然!逻辑一定要严密

猜你喜欢

转载自blog.csdn.net/qq_28306361/article/details/88525541