leetcode之Binary Tree Preorder Traversal(144)

题目:

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

python代码1:(递归版)

class Solution:
    def preorderTraversal(self, root):
        if root == None:
            return []
        elif root.left == None and root.right == None:
            return [root.val]
        else:
            return [root.val] + self.preorderTraversal(root.left)  + self.preorderTraversal(root.right)

非递归版过段时间补上。

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/81282364