zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):145-Binary Tree Postorder Traversal

    题目来源:

      https://leetcode.com/problems/binary-tree-postorder-traversal/


    题意分析:

      后序遍历一棵树,递归的方法很简单,尝试用非递归的方法。


    题目思路:

      后序遍历的顺序是,先左子树,再右子树,最后才是根节点。递归的思想很简单,那么非递归的方法也是利用栈来实现,后进先出,不过这里先进的应该是左子树,那么得到的结果是根节点,右子树接着左子树。最后将结果翻转就可以了。代码给的是非递归的方法。


    代码(python):

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def postorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            ans = []
            if root == None:
                return ans
            stack = [root]
            while len(stack) != 0:
                p = stack.pop()
                ans.append(p.val)
                if p.left:
                    stack.append(p.left)
                if p.right:
                    stack.append(p.right)
            ans.reverse()
            return ans
    View Code
  • 相关阅读:
    训练赛
    树形dp专题
    返回的中文乱码问题
    富文本内容放在xml标签中;
    xml 截取 标签中的字符串;字符串去掉空格
    Intetn 传输 (2)
    安卓修改标题栏
    简单的数据存储(SharedPreferences.Editor)
    Intent的数据传输
    python实现快排+冒泡排序
  • 原文地址:https://www.cnblogs.com/chruny/p/5477575.html
Copyright © 2011-2022 走看看