1. 程式人生 > >二叉樹先序遍歷(非遞歸)

二叉樹先序遍歷(非遞歸)

for fin light list 先序 int eno 遞歸 none

二叉樹的先序遍歷(非遞歸)特別簡單

直接上代碼,根節點先入棧,然後循環棧不為空,pop出來後讓右節點和左節點分別入棧

# 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]
        """
        if root==None:
            return []
        stack=[root]
        result=[]
        while len(stack)!=0:
            cur=stack.pop()
            result.append(cur.val)
            if cur.right!=None:
                stack.append(cur.right)
            if cur.left!=None:
                stack.append(cur.left)
        return result

二叉樹先序遍歷(非遞歸)