(python的坑,坑的我头晕,下行循环写后根遍历)


总是提示越界错误
IndexError: list index out of range
### if s and s[-1].left == t:
需要先判断s是否为空,假如:if s[-1].left == t and s就会出现越界。
## 边界条件的非常非常重要!!!!


## 代码如下:
```python
class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        ans = []
        s = []
        t = root
        temp =t.item
        while t is not None or s:
            while t is not None:
                s.append(t)
                t = t.left if t.left is not None else t.right
            
            t = s.pop()
            ans += [t.item]
            print ans
         
            if s and s[-1].left == t:
                t = s[-1].right
            else:
                t = None
                
        return ans

猜你喜欢

转载自blog.csdn.net/weixin_40759186/article/details/83348431