【LeetCode】【Python】Binary Tree Inorder Traversal

来源:互联网 发布:淘宝做单一个月挣多少 编辑:程序博客网 时间:2024/06/04 17:57

Given a binary tree, return the inorder traversal of its nodes' values.

For example:

Given binary tree {1,#,2,3},


比较简单,就是转化成中序遍历即可,访问顺序是中序遍历左子树,根节点,中序遍历右子树


Python编程的时候需要注意,要在返回单一数字的时候加上中括号【】,否则Python不知道这是一个list


# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @return a list of integers    def inorderTraversal(self, root):        if root is None:            return []        elif root.left is None and root.right is None:            return [root.val]        else:            return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right)




0 0
原创粉丝点击