Wildcard Matching (Python)
Binary Tree Inorder Traversal (Python)

Binary Tree Preorder Traversal (Python)

kitt posted @ 2014年2月12日 20:08 in LeetCode , 3026 阅读

非递归先序遍历二叉树, 弹栈print, 右子节点入栈, 再左子节点入栈。

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def preorderTraversal(self, root):
        res = []
        if root == None:
            return res
        stack = [root]
        while stack:
            root = stack.pop()
            res.append(root.val)
            if root.right:
                stack.append(root.right)
            if root.left:
                stack.append(root.left)
        return res
Avatar_small
alexchonglian 说:
2014年11月12日 15:00

def preorderTraversal(self, root):
if root == None: return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)

Avatar_small
123 说:
2014年11月12日 20:04

要求非递归...@alexchonglian:


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter