[LeetCode]题解(python):144-Binary Tree Preorder Traversal

题目来源:

  https://leetcode.com/problems/binary-tree-preorder-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 preorderTraversal(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.right:
                stack.append(p.right)
            if p.left:
                stack.append(p.left)
        return ans
View Code
原文地址:https://www.cnblogs.com/chruny/p/5477537.html